I'm wondering about an elegant way allowing to sum (or calculate a mean) a numeric values of a list. e.g.
x <- list( a = matrix(c(1,2,3,4), nc=2), b = matrix(1, nc=2, nr=2))
and want to get
x[[1]]+x[[2]]
or a mean:
(x[[1]]+x[[2]])/2
You can use Reduce to successively apply a binary function to elements in a list.
Reduce
Reduce("+",x) [,1] [,2] [1,] 2 4 [2,] 3 5 Reduce("+",x)/length(x) [,1] [,2] [1,] 1.0 2.0 [2,] 1.5 2.5
1.4m articles
1.4m replys
5 comments
57.0k users