4

I have a matrix with zeros.

mm<-matrix(0,10,5)

and I have the data.frame l with two columns that contains the row and column numbers where the value 3 must be put in the matrix mm.

Here is l:

   row_in_a   column_in_a
1   2             4
2   5             3
3   7             2
4   1             5
5   3             2
6   .             .
7   etc           etc

I made this function

 for(i in 1:length(l[,1])){
     mm[l[i,1],l[i,2]]<-3}
     return(mm)
 }   

      [,1] [,2] [,3] [,4] [,5]
[1,]    0    0    0    0    3
[2,]    0    0    0    3    0
[3,]    0    3    0    0    0
[4,]    0    0    0    0    0
[5,]    0    0    3    0    0
[6,]    0    0    0    0    0
[7,]    0    3    0    0    0
[8,]    0    0    0    0    0
[9,]    0    0    0    0    0
[10,]   0    0    0    0    0 

Would it be possible to have the same result without using the for loop?

plannapus
  • 18,529
  • 4
  • 72
  • 94
sdhaoui
  • 369
  • 1
  • 10

0 Answers0