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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 08:08:19  来源:igfitidea点击:

lapply function /loops on list of lists R

rlistloopslapply

提问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 lapplyfunction or a simple loop to datalist 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 liststructure, a nested lapplycan be used

或者,如果您需要具有list结构的输出,lapply则可以使用嵌套

 lapply(data, lapply, mean)

Or with rapply, we can use the argument howto get what kind of output we want.

或者使用rapply,我们可以使用参数how来获得我们想要的输出类型。

  rapply(data, mean, how='list')

If we are using a forloop, 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]])
    }
   }