Using a double loop to fill a matrix in R
1 answer
Thus, there are two problems here. First your inner loop for(...)
refers to columns 3: 4, but there are only 2 columns.
Second, you define a matrix to have single values in the elements, but then you try to set each element to a vector.
If you really want a matrix of vectors, you can do it this way.
mat<-matrix(list(c(NA,NA)), nrow=2, ncol=2)
for (i in 1:2){
for (j in 1:2){
mat[i,j][[1]]<-c(i,j)
}
}
mat
# [,1] [,2]
# [1,] Integer,2 Integer,2
# [2,] Integer,2 Integer,2
mat[1,1]
# [[1]]
# [1] 1 1
+1
source to share