In addition to my earlier question R: How to match/join 2 matrices of different dimensions (nrow/ncol)? I need a loop as I have a list of more than 1000 matrices. I decide to use the code (from the answers)
full_matrix[rownames(full_matrix) %in% rownames(small_matrix), colnames(full_matrix) %in% colnames(small_matrix)] <- small_matrix
which worked fine in my case for a single matrix match. However, I have problems implementing this code into a loop for the list
of matrices
"small_matrix". Here my code:
full_matrix <- list() for(i in 1:length(small_matrix)) { full_matrix[i][rownames(full_matrix[i]) %in% rownames(small_matrix[i]), colnames(full_matrix[i]) %in% colnames(small_matrix[i])] <- small_matrix[i] }
I get the error: incorrect number of subscripts on matrix
, which is probably due to a wrong indexing in my basic knowledge of loops. I appreciate any help. Thanks
NEW EDIT according to answer of @Jim M.: Your answer works fine for this example but the small_matrix(ces) should be created as well in a loop like in this former question. Here you find the code example:
library(abind) a = c("A", "B", "C", "D", "E", "F") full_matrix = array(dim=c(6,6,2)) dimnames(full_matrix) <- list(levels(as.factor(a)), levels(as.factor(a)), c("mat1","mat2"))
as @Jim M. advises. And here the new code:
##### new part for small matrix df_import <- data.frame(OC = c("A", "A", "B", "B", "C", "C", "D", "D"), TC = c("Z", "Z", "Y", "Y", "X", "X", "W", "W"), Value = c(1,2,3,4,5,6,7,8), Year = c(2010,2011)) Import_Year <- split(df_import, df_import$Year) library(reshape2) small_matrix <- list() for(i in 1:length(unique(Import_Year))) { small_matrix[[length(small_matrix)+1]] <- dcast(OC ~ TC, data =Import_Year[[i]], value.var = "Value") } small_matrix ##### end new part
and than further the for-loop of @Jim. M:
for(i in seq_along(small_matrix_list)){ afill(full_matrix[, , i], local= TRUE ) <- small_matrix[[i]] }
However, I get the following error message:
Error in `afill<-.default`(`*tmp*`, local = TRUE, value = list(OC = 1:4, : 'x' must have names on dimensions corresponding to those in 'value'
Any ideas? Thanks