Often you may want to sum the values in a matrix in R in a specific way.
Fortunately this is easy to do and you can use the following methods to do so:
Method 1: Sum All Values in Matrix
#sum all values in matrix
sum(my_matrix)
This particular example will sum all of the values in the entire matrix of the matrix named my_matrix.
Method 2: Sum Values in Each Column of Matrix
#sum values in each column of matrix
colSums(my_matrix)
This particular example will return the sum of each column of the matrix named my_matrix.
Method 3: Sum Values in Each Row of Matrix
#sum values in each row of matrix
rowSums(my_matrix)
This particular example will return the sum of each row of the matrix named my_matrix.
The following examples show how to use each of these methods in practice with the following matrix in R named my_matrix:
#create matrix
my_matrix <- matrix(1:20, ncol=5)
#specify column names for matrix
colnames(my_matrix) <- c('A', 'B', 'C', 'D', 'E')
#view matrix
my_matrix
A B C D E
[1,] 1 5 9 13 17
[2,] 2 6 10 14 18
[3,] 3 7 11 15 19
[4,] 4 8 12 16 20
Example 1: Sum All Values in Matrix
We can use the following syntax to sum all of the values in the entire matrix:
#sum all values in matrix
sum(my_matrix)
A B D E
[1,] 1 5 13 17
[2,] 2 6 14 18
[3,] 3 7 15 19
[4,] 4 8 16 20
This returns a value of 210, which represents the sum of all values in the entire matrix.
Example 2: Sum Values in Each Column of Matrix
We can use the following syntax to calculate the sum of values in each column of the matrix:
#sum values in each column of matrix
colSums(my_matrix)
A B C D E
10 26 42 58 74
This returns the sum of each column in the matrix.
For example, we can see:
- The sum of values in column A is 10.
- The sum of values in column B is 26.
- The sum of values in column C is 42.
- The sum of values in column D is 58.
- The sum of values in column E is 74.
Example 3: Sum Values in Each Row of Matrix
We can use the following syntax to calculate the sum of values in each row of the matrix:
#sum values in each row of matrix
rowSums(my_matrix)
[1] 45 50 55 60
This returns the sum of each row in the matrix.
For example, we can see:
- The sum of values in row 1 is 45.
- The sum of values in row 2 is 50.
- The sum of values in row 3 is 55.
- The sum of values in row 4 is 60.
Note that we can also use the cbind function to bind these row sums to the end of the matrix if we’d like:
#sum values in each row of matrix and bind as new column to matrix
cbind(my_matrix, rowSums(my_matrix))
A B C D E
[1,] 1 5 9 13 17 45
[2,] 2 6 10 14 18 50
[3,] 3 7 11 15 19 55
[4,] 4 8 12 16 20 60
The row sums now appear as the last column in the matrix.
Note: The cbind function is used to “column-bind” together objects in R.
Additional Resources
The following tutorials explain how to perform other common tasks in R:
How to Sort a Matrix in R
How to Remove NA from Matrix in R
How to Convert Data Frame to Matrix in R
How to Convert a Table to a Matrix in R