VOOZH about

URL: https://www.geeksforgeeks.org/r-language/sum-all-elements-in-a-matrix-using-r/

⇱ Sum All Elements in a Matrix using R - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sum All Elements in a Matrix using R

Last Updated : 23 Jul, 2025

Matrices in R Programming Language are the objects in which the elements are arranged in a 2-D rectangular layout. A matrix is a collection of elements of the same data type(numeric, character, or logical) arranged in a fixed number of rows and columns, as we very well know rows are represented horizontally and columns are represented vertically.

Creating Matrix

To create a matrix in R, we use the matrix() function. This function takes several arguments, including data(collection of elements), nrow, ncol, byrow.

Syntax: matrix(data, nrow, ncol, byrow=True)

  • data :- It will describe the collection of elements that R will arrange into rows and columns of the matrix.
  • nrow :- Describe the number of rows
  • ncol :- Describes the number of columns
  • byrow :- By default this field is set to "FALSE" means elements in the matrix are filled in column wise manner but if we explicitly set it to "TRUE" then elements in the matrix are filled in the row wise manner.

Output:

My 3*3 matrix :-
[,1] [,2] [,3]
[1,] 10 20 30
[2,] 40 50 60
[3,] 70 80 90

Accessing elements in different forms in the matrix

Suppose we have a 3*3 matrix i.e. 9 elements and now we need to access each element separately. Let's examine an example code to understand this.

Output:

My 3*3 matrix is:
[,1] [,2] [,3]
[1,] 10 20 30
[2,] 40 50 60
[3,] 70 80 90
Element at position ( 1 , 1 ) is: 10
Element at position ( 1 , 2 ) is: 20
Element at position ( 1 , 3 ) is: 30
Element at position ( 2 , 1 ) is: 40
Element at position ( 2 , 2 ) is: 50
Element at position ( 2 , 3 ) is: 60
Element at position ( 3 , 1 ) is: 70
Element at position ( 3 , 2 ) is: 80
Element at position ( 3 , 3 ) is: 90

Sum all elements in a matrix using R

Now, we are now well-equipped to calculate the sum of all elements in a matrix. We have above covered the process of matrix creation and explored various methods of accessing its elements.

Output:

MY 3*3 matrix is:
[,1] [,2] [,3]
[1,] 10 20 30
[2,] 40 50 60
[3,] 70 80 90
Sum of all elements in the matrix are: 450

Adding sum of the matrix element row by row

Output:

 [,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
Sum of elements in row 1 : 6
Sum of elements in row 2 : 15
Sum of elements in row 3 : 24
Total sum of all elements: 45

Adding sum of the matrix element by column

Output:

 [,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
Sum of elements in column 1 : 12
Sum of elements in column 2 : 15
Sum of elements in column 3 : 18
Total sum of all elements: 45
Comment
Article Tags:
Article Tags:

Explore