lapply function /loops on list of lists R

27,923

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]])
    }
   }
Share:
27,923
MIH
Author by

MIH

Updated on July 23, 2020

Comments

  • MIH
    MIH almost 4 years

    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.