Add all elements to matrix R

I am trying to add all elements to a matrix. This is an example of my matrix (the actual matrix is โ€‹โ€‹bigger):

m = matrix(c(528,479,538,603),nrow=2,ncol=2) m AB male 528 538 female 479 603 

I am trying to do:

  sum.elements = colSums(colSums(m)) 

but it gives the following error:

Error in colSums (colSums (m)): 'x' must be an array of at least two Dimensions

I tried to do:

 x = colSums(m) sum.elements = x[1] + x[2] 

but that would be very long if you have a matrix with 100 columns ...

Any help would be greatly appreciated!

+7
source share
2 answers

You can do sum . It also has the na.rm option to remove NA values.

  sum(m) #[1] 2148 

In general, sum works for vector , matrix and data.frame

Benchmarks

  set.seed(24) m1 <- matrix(sample(0:20, 5000*5000, replace=TRUE), ncol=5000) system.time(sum(m1)) # user system elapsed # 0.027 0.000 0.026 system.time(sum(colSums(m1))) # user system elapsed # 0.027 0.000 0.027 system.time(Reduce('+', m1)) # user system elapsed #25.977 0.644 26.673 
+9
source

Reduce will work

  Reduce(`+`,m) [1] 2148 
+3
source

All Articles