I have a matrix with zeros.
mm<-matrix(0,10,5)
and I have a data.frame lwith two columns that contain the row and column numbers, where the value 3 should be placed in the matrix mm.
Here 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
Is it possible to get the same result without using a loop for?
source
share