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
Sum Of Elements In A List Using The sum() Function. Python also provides us with an inbuilt sum() function to calculate the sum of the elements in any collection object. The sum() function accepts an iterable object such as list, tuple, or set and returns the sum of the elements in the object.
Python's built-in function sum() is an efficient and Pythonic way to sum a list of numeric values. Adding several numbers together is a common intermediate step in many computations, so sum() is a pretty handy tool for a Python programmer.
You can use Reduce
to successively apply a binary function to elements 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With