lapply function /loops on list of lists R

泄露秘密 提交于 2020-04-07 11:00:30

问题


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

or by:

lapply(data1,mean)

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

rapply(data,mean)

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


回答1:


We can loop through the list of list with a nested 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

 lapply(data, lapply, mean)

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

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

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


来源:https://stackoverflow.com/questions/31561238/lapply-function-loops-on-list-of-lists-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!