16

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
Michael Ohlrogge
  • 10,559
  • 5
  • 48
  • 76
hora
  • 845
  • 5
  • 14
  • 25
  • 2
    if you use `lapply` over a single element of the list, you're going to take the mean of each element of the vector. use `lapply(list, mean)` instead. Also, using `list` as a variable name is a bad idea since its an important function! – Justin Nov 12 '12 at 23:28

2 Answers2

15

To get the mean of the 7th element of the list just use mean(list[[7]]). To get the mean of each element of the list use lapply(list,mean). And it's a really bad idea to call your list list.

  • Thank you :) and I will change the name as well – hora Nov 12 '12 at 23:35
  • @hora if you feel this answer provided you with an adequate description of what you were looking for, feel free to accept it as correct by checking the grey check mark below the score. – Roman Luštrik Nov 12 '12 at 23:47
12

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
Community
  • 1
  • 1
Ricardo Saporta
  • 54,400
  • 17
  • 144
  • 178