Create a large list in R with a loop
I have a problem with this:
I need to create a list of matrices. Here is the data frame:
data=data.frame("Node"=c(1:5), posx=c(2,3,6,8,1), posy=c(1,1,4,7,8))
Node posx posy
1 1 2 1
2 2 3 1
3 3 6 4
4 4 8 7
5 5 1 8
Now I want to create a list of matrices. With Loop. I want to create a list of matrices like this:
l=list(l1,l2,l3,l4,l5)
Where:
l1=cbind(c(2),c(1))
l2=cbind(c(3),c(1))
l3=cbind(c(6),c(4))
l4=cbind(c(8),c(7))
l5=cbind(c(1),c(8))
And here's my attempt:
for (i in 1:(data$Node) ) {
l=list(cbind(c(data$posx[i]), (data$posy[i])))
}
+3
source to share
2 answers
Try
lapply(seq_len(nrow(data)), function(i) as.matrix(data[i,-1]))
or
lapply(split(data[,-1],row(data)[,1]), as.matrix)
or
lapply(split(as.matrix(data[,-1]),row(data)[,1]), matrix, ncol=2)
Or using data.table
library(data.table)
setDT(data)[,list(list(as.matrix(.SD))) , by=Node]$V1
+3
source to share