How to apply mean function over elements of a list in R

55,285

consider using sapply instead of lapply.

# sample data
a<- 1:3
dat <- list(a, a*2, a*3)

# sapply gives a tidier output
> sapply(dat, mean)
[1] 2 4 6

> lapply(dat, mean)
[[1]]
[1] 2

[[2]]
[1] 4

[[3]]
[1] 6



Also, you might want to take a look at the plyr package. This question also does a good job of explaining the different *apply functions
Share:
55,285
hora
Author by

hora

Updated on August 27, 2020

Comments

  • hora
    hora over 3 years

    I have a list and I want to use lapply() to compute the mean of its elements. For example, for the seventh item of the list I have:

    >list[[7]]
     [1] 1 1 1 1 1 1 1 1 1 1
    

    and my output should be:

    > mean(temp[[7]][1:10])
    [1] 1
    

    But when I use lapply() like below the result would be something else. What should I do?

    > lapply(list[[7]][1:10],mean)
    [[1]]
    [1] 1
    
    [[2]]
    [1] 1
    .
    .
    .
    [[10]]
    [1] 1