Search code examples
rloopslapplysapply

Mean of one vector of list of lists


I have following data set

myList <- split(x = ChickWeight, f = ChickWeight$Diet)

and i want to calculate the average of weights by list, i.e four different averages. one possible solution is

a<-lapply(myList, `[[`, 1)
lapply(a, mean)

But is it possible if i can have mean function in "a". i.e

a<-lapply(myList, `[[`, 1, mean)

Solution

  • You could define a function colMean to use in lapply.

    colMean <- function(x, col) colMeans(x[, col, drop=FALSE])
    
    lapply(myList, colMean, col='weight')  ## also: `col=1`
    # $`1`
    # weight 
    # 102.6455 
    # 
    # $`2`
    # weight 
    # 122.6167 
    # 
    # $`3`
    # weight 
    # 142.95 
    # 
    # $`4`
    # weight 
    # 135.2627 
    

    Also works for multiple columns.

    lapply(myList, colMean, col=c('weight', 'Time')
    # $`1`
    # weight      Time 
    # 102.64545  10.48182 
    # 
    # $`2`
    # weight      Time 
    # 122.61667  10.91667 
    # 
    # $`3`
    # weight      Time 
    # 142.95000  10.91667 
    # 
    # $`4`
    # weight      Time 
    # 135.26271  10.75424