Add all elements in matrix R
Reduce
will work
Reduce(`+`,m)
[1] 2148
You can do sum
. It also has the option na.rm
to remove the 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