Compute the Sum of Rows of a Matrix or Array in R Programming – rowSums Function

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)

chevron_right


Output:

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

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)

chevron_right


Output:

,, 1

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

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

[1] 16 20
My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.