Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum a numeric list elements

Tags:

r

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 
like image 924
user1160354 Avatar asked Jan 20 '12 10:01

user1160354


People also ask

How do you sum elements in a list?

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.

Can you sum a list in Python?

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.


1 Answers

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 
like image 146
James Avatar answered Oct 22 '22 13:10

James