Skip to content
Related Articles

Related Articles

Compute the Sum of Rows of a Matrix or Array in R Programming – rowSums Function
  • Last Updated : 03 Jun, 2020

rowSums() function in R Language is used to compute the sum of rows of a matrix or an array.

Syntax: rowSums(x, na.rm = FALSE, dims = 1)

Parameters:
x: array or matrix
dims: Integer: Dimensions are regarded as ‘rows’ to sum over. It is over dimensions dims+1, ….

Example 1:




# R program to illustrate
# rowSums() function
  
# Initializing a matrix 
x <- matrix(rep(2:10), 3, 3)
  
# Printing Matrix
print(x)
  
# Calling the rowSums() function
rowSums(x)

Output:



     [, 1] [, 2] [, 3]
[1, ]    2    5    8
[2, ]    3    6    9
[3, ]    4    7   10
[1] 15 18 21

Example 2:




# R program to illustrate
# rowSums function
  
# Initializing a 3D array
x <- array(1:8, c(2, 2, 2))
  
# Printing the array
print(x)
  
# Calling the rowSums() function
rowSums(x, dims = 1)

Output:

,, 1

     [, 1] [, 2]
[1, ]    1    3
[2, ]    2    4,, 2

     [, 1] [, 2]
[1, ]    5    7
[2, ]    6    8

[1] 16 20

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :