在列表R上应用lapply函数/loops [英] lapply function /loops on list of lists R

查看:82
本文介绍了在列表R上应用lapply函数/loops的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个话题曾出现过几次,但是示例通常更复杂,我想对这种简单情况有一个答案(或一套可行的解决方案).我仍然会全神贯注于R和程序设计.因此,在这里我想使用lapply函数或data list的简单循环,该列表是三个向量列表的列表.

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.

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)
}

或通过:

lapply(data1,mean)

而且我知道如何使用rapply来获得所有手段:

and I know how to get all the means using rapply:

rapply(data,mean)

问题是rapply不能维护列表结构. 帮助和可能的一些提示/解释将不胜感激.

The problem is that rapply does not maintain the list structure. Help and possibly some tips/explanations would be much appreciated.

推荐答案

我们可以使用嵌套的lapply/sapply

 lapply(data, sapply, mean)

否则写为

 lapply(data, function(x) sapply(x, mean))

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

Or if you need the output with the list structure, a nested lapply can be used

 lapply(data, lapply, mean)

或者使用rapply,我们可以使用参数how来获得所需的输出类型.

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

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

如果使用的是for循环,则可能需要创建一个对象来存储结果.

If we are using a for loop, we may need to create an object to store the results.

  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]])
    }
   }

这篇关于在列表R上应用lapply函数/loops的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆