How to sum the numeric elements of a list in R

I'm curious about the elegant way to summarize (or calculate the average) the numerical values โ€‹โ€‹of a list. eg.

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 average value:

 (x[[1]]+x[[2]])/2 
+23
r
Jan 20 2018-12-12T00:
source share
1 answer

You can use Reduce to sequentially apply a binary function to items in a list.

 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 
+51
Jan 20 '12 at 10:38
source share



All Articles