简体   繁体   English

创建列表列表的有效方法

[英]efficient way to create a list of lists

I am using lapply and mapply to create a bunch of operations. 我正在使用lapply和mapply创建一堆操作。 My data is composed of lists. 我的数据由列表组成。

For one of the calculations I am having some problems on how to use any of the apply functions. 对于其中一种计算,我在如何使用任何apply函数方面遇到一些问题。 This is an example of what I want to do: 这是我想做的一个例子:

#list with a collection of objects, each object has a vector with the their 2 closest neighbors identification. 
list_a<-list(c(2,4),c(1,3),c(1,4),c(3,2))

#list with the obs of each point
list_obs<-list(runif(1000,1,2),runif(1000,0,2),runif(1000,0.5,2),runif(1000,0.1,1.5))

position n in list_a corresponds to the neigh. list_a中的位置n对应于邻居。 points of point n n的点

position n in list_obs corresponds to observations of point n list_obs中的位置n对应于点n观测值

What I want to do is to create a new list that will store in each position n the list of observations of the neighb. 我想要做的是创建将在每个位置存储一个新的列表n的neighb的观察名单。 points: 要点:

#output
 out=list(list(list_obs[[2]],list_obs[[4]]),list(list_obs[[1]],list_obs[[3]]),list(list_obs[[1]],list_obs[[4]]),list(list_obs[[3]],list_obs[[2]]))
> str(out)
List of 4
 $ :List of 2
  ..$ : num [1:1000] 1.673 1.423 0.228 1.758 1.65 ...
  ..$ : num [1:1000] 0.679 1.341 0.148 0.867 0.724 ...
 $ :List of 2
  ..$ : num [1:1000] 1.25 1.5 1.58 1.54 1.6 ...
  ..$ : num [1:1000] 0.526 1.545 1.848 0.711 0.697 ...
 $ :List of 2
  ..$ : num [1:1000] 1.25 1.5 1.58 1.54 1.6 ...
  ..$ : num [1:1000] 0.679 1.341 0.148 0.867 0.724 ...
 $ :List of 2
  ..$ : num [1:1000] 0.526 1.545 1.848 0.711 0.697 ...
  ..$ : num [1:1000] 1.673 1.423 0.228 1.758 1.65 ...

Can anyone advise me on the best way to do this? 有人可以建议我这样做的最佳方法吗?

My data is huge, so a loop will take 2 much time to run. 我的数据非常庞大,因此循环需要2个多时间来运行。 The data is composed of 3000 points (with 3000-1 neigh.), each point with +20.000 observations. 数据由3000个点(与3000-1相邻)组成,每个点具有+20.000个观测值。

您是否尝试过以下命令?

lapply(list_a, function(x) list_obs[x])
lapply(list_a,FUN=function(x)lapply(x,FUN=function(y)list_obs[y]))

but, as per comments, there might be a better way to do it 但是,根据评论,可能会有更好的方法

sorry saw that was just answered! 抱歉看到刚才回答了!

lapply(list_a,FUN=function(x)list_obs[x]) 

is better! 更好!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM