lapply function /loops on list of lists R

前端 未结 1 1115
死守一世寂寞
死守一世寂寞 2021-01-30 07:32

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 situa

相关标签:
1条回答
  • 2021-01-30 08:17

    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]])
        }
       }
    
    0 讨论(0)
提交回复
热议问题