list lapply 函数 /loops 在列表 R 上
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31561238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
lapply function /loops on list of lists R
提问by MIH
I know this topic appeared on SO a few times, but the examples were often more complicated and I would like to have an answer (or set of possible solutions) to this simple situation. I am still wrapping my head around R and programming in general. So here I want to use lapply
function or a simple loop to data
list which is a list of three lists of vectors.
我知道这个话题在 SO 上出现过几次,但例子通常更复杂,我想对这个简单的情况有一个答案(或一组可能的解决方案)。我仍然在围绕 R 和一般编程。所以在这里我想使用lapply
函数或一个简单的循环来data
列出它是三个向量列表的列表。
data1 <- list(rnorm(100),rnorm(100),rnorm(100))
data2 <- list(rnorm(100),rnorm(100),rnorm(100))
data3 <- list(rnorm(100),rnorm(100),rnorm(100))
data <- list(data1,data2,data3)
Now, I want to obtain the list of means for each vector. The result would be a list of three elements (lists).
现在,我想获得每个向量的均值列表。结果将是三个元素(列表)的列表。
I only know how to obtain list of outcomes for a list of vectors and
我只知道如何获取向量列表的结果列表和
for (i in 1:length(data1)){
means <- lapply(data1,mean)
}
or by:
或通过:
lapply(data1,mean)
lapply(data1,mean)
and I know how to get all the means using rapply
:
我知道如何使用rapply
以下方法获得所有方法:
rapply(data,mean)
rapply(data,mean)
The problem is that rapply does not maintain the list structure. Help and possibly some tips/explanations would be much appreciated.
问题是 rapply 不维护列表结构。帮助和可能的一些提示/解释将不胜感激。
回答by akrun
We can loop through the list of list with a nested lapply/sapply
我们可以使用嵌套的列表遍历列表 lapply/sapply
lapply(data, sapply, mean)
It is otherwise written as
否则写为
lapply(data, function(x) sapply(x, mean))
Or if you need the output with the list
structure, a nested lapply
can be used
或者,如果您需要具有list
结构的输出,lapply
则可以使用嵌套
lapply(data, lapply, mean)
Or with rapply
, we can use the argument how
to get what kind of output we want.
或者使用rapply
,我们可以使用参数how
来获得我们想要的输出类型。
rapply(data, mean, how='list')
If we are using a for
loop, we may need to create an object to store the results.
如果我们使用for
循环,我们可能需要创建一个对象来存储结果。
res <- vector('list', length(data))
for(i in seq_along(data)){
for(j in seq_along(data[[i]])){
res[[i]][[j]] <- mean(data[[i]][[j]])
}
}