Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a big list in R with loop

Tags:

loops

r

matrix

I have a problem with this:
I need a create a list of matrices. Here is a 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 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 is my try:

for (i in 1:(data$Node) ) {
  l=list(cbind(c(data$posx[i]), (data$posy[i])))
}
like image 405
sgt Fury Avatar asked Dec 05 '25 08:12

sgt Fury


1 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
like image 193
akrun Avatar answered Dec 07 '25 20:12

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!