Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
265 views
in Technique[技术] by (71.8m points)

lapply function /loops on list of lists R

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...