Using a double loop to fill a matrix in R

I am using a double loop to fill the matrix using the following code.

mat<-matrix(NA, nrow=2, ncol=2)

for (i in 1:2){
 for (j in 3:4){
   mat[i,j]<-c(i,j)
     }
}
mat

      

The error I am getting:

Error in '[<-'('*tmp*', i, j, value = c(3L, 1L)) : 
  subscript out of bounds

      

What am I doing wrong?

0


source to share


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







All Articles