I am trying to add all the elements in 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
A B
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 have tried doing:
x = colSums(m)
sum.elements = x[1] + x[2]
but this would be very long when you have a 100-column matrix...
Any help would be greatly appreciated!
How to add a value to a particular matrix element in R? To add a value to a particular matrix element in R, we can use subsetting for the particular value with single square brackets. For Example, if we have a matrix called M and we want to add 10 to the fifth value in second column then can use the below mentioned command −
Here you have every possibility: x <- matrix(1:9, 3, 3) add 5 to column 1: x[, 1] + 5 add 5 to row 1: x[1, ] + 5 add 1 to the first row, 2 to second, 3 to third: x + 1:3 the same with columns: t(t(x) + 1:3) add 5 to all the cells: x + 5 Share Cite Improve this answer Follow answered Dec 4 '14 at 13:31 Tim♦Tim
We can apply a function to each element of a Matrix, or only to specific dimensions, using apply (). apply (X, MARGIN, FUN, ...) MARGIN is a vector giving the subscripts which the function will be applied over. For a matrix 1 indicates rows, 2 indicates columns, c (1,2) indicates rows and columns.
A common operation with matrix is to transpose it. This can be done with the function t (). We can add row or column using rbind () and cbind () function respectively. Similarly, it can be removed through reassignment.
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
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
Reduce
will work
Reduce(`+`,m)
[1] 2148
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