Ben
Ben

Reputation: 125

in R:how to store number by order in list

Suppose I have a for loop like following

for(i in 1:2)
{
  eigeni=lapply(rho,function(mat) eigen(mat[1:i,1:i])$values)
  x=lapply(eigeni,function(x) i-sum(ifelse(x>1,x,1)-1))
}

When i=1,x is

> x
$rs6139074
[1] 0.241097

$rs1418258
[1] 0.241097

When i=2,x is

> x
$rs6139074
[1] 1.241097

$rs1418258
[1] 1.247

How can I store x by column for each iteration like following after this loop? I would like something like following

for(i in 1:2)
    {
      eigeni=lapply(rho,function(mat) eigen(mat[1:i,1:i])$values)
      x[i]=lapply(eigeni,function(x) i-sum(ifelse(x>1,x,1)-1))
    }


 > x
 $rs6139074
 [1] 0.241097 1.241097

 $rs1418258
 [1] 0.241097 1.247

Following Dave2e answer I got

> mylist
[[1]]
[[1]]$rs6139074
[1] 0.241097

[[1]]$rs1418258
[1] 0.241097


[[2]]
[[2]]$rs6139074
[1] 1.241097

[[2]]$rs1418258
[1] 1.247

Upvotes: 2

Views: 111

Answers (1)

Dave2e
Dave2e

Reputation: 24079

One of the easiest ways is to define a empty list and append values onto it:

mylist<-list()

for(i in 1:2)
{
  eigeni=lapply(rho,function(mat) eigen(mat[1:i,1:i])$values)
  x=lapply(eigeni,function(x) i-sum(ifelse(x>1,x,1)-1))
  mylist[[i]]<-x
}
print(mylist)

Of course if you can use the lapply function, that would be the most condensed and most likely fastest method.

Upvotes: 1

Related Questions