Search code examples
rlistmean

How to get the mean of same name elements of list


I have made a function that runs a bootstrapped regression (with plm). I've managed to get a list, that contains a list for every repetition. Inside that sub-list, there are two coefficients each one with its name.

So I want to know if I can get the mean of each coefficient, by calling it just for the name.

The minimal example I could do was with three repetitions so the list looks like this:

> dput(b)
list(list(capital = 0.185108300831744, labor = 0.342750547967331), 
    list(capital = 0.219370274172395, labor = 0.302455636315905), 
    list(capital = 0.191813145986764, labor = 0.317630069307932))

So the desired result is a list with the mean for capital and the mean for labor, like this:

> dput(result)
list(capital = 0.1987639, labor = 0.3209454)

Thanks in advance!


Solution

  • Here's a base R solution:

    b <- list(list(capital = 0.185108300831744, labor = 0.342750547967331), 
              list(capital = 0.219370274172395, labor = 0.302455636315905), 
              list(capital = 0.191813145986764, labor = 0.317630069307932))
    
    my_names <- c('capital', 'labor')
    result <- lapply(my_names, \(x) mean(sapply(b, '[[', x)))
    names(result) <- my_names
    
    result
    
    $capital
    [1] 0.1987639
    
    $labor
    [1] 0.3209454
    

    Alternately, we can take advantage of the fact that lists can be treated as data frames:

    result <- colMeans(do.call(rbind, lapply(b, as.data.frame)))
    
      capital     labor 
    0.1987639 0.3209454