Reputation: 659
I have four vectors:
a<-c(1,2,3,4,5)
b<-c(2,3,4,5,6)
c<-c(3,5,6,7,2)
d<-c(5,7,3,7,2)
I want to calculate the average so that I get:
average
2.75 4.25 4.00 5.75 3.75
Could anybody give me an advice on how I can do this? Thank you.
Upvotes: 1
Views: 427
Reputation: 5536
Solution with mapply
:
mapply(function(...) mean(c(...)), a, b, c, d)
Solution with Reduce
:
l <- list(a,b,c,d)
Reduce(`+`, l) / length(l)
Solution with double sapply
:
l <- list(a,b,c,d)
sapply(seq_along(a), function(i) mean(sapply(l, function(x) x[i])))
Upvotes: 2
Reputation: 42659
Put them in a matrix and use rowMeans
:
a<-c(1,2,3,4,5)
b<-c(2,3,4,5,6)
c1<-c(3,5,6,7,2)
d<-c(5,7,3,7,2)
rowMeans(matrix(c(a,b,c1,d), ncol=4))
## [1] 2.75 4.25 4.00 5.75 3.75
Upvotes: 1