Calculate the Sum of Matrix or Array columns in R Programming – colSums() Function

colSums() function in R Language is used to compute the sums of matrix or array columns.

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

Parameters:
x: matrix or array
dims: this is integer value whose dimensions are regarded as ‘columns’ to sum over. It is over dimensions 1:dims.

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

# R program to illustrate
# colSums function
  
# Initializing a matrix with 3 
# rows and 3 columns
x <- matrix(rep(1:9), 3, 3)
  
# Getting the matrix representation
x
  
# Calling the colSums() function
colSums(x)

chevron_right


Output:

     [, 1] [, 2] [, 3]
[1, ]    1    4    7
[2, ]    2    5    8
[3, ]    3    6    9

[1]  6 15 24

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# R program to illustrate
# colSums function
  
# Initializing a 3D array
x <- array(1:12, c(2, 3, 3))
  
# Getting the array representation
x
  
# Calling the colSums() function
colSums(x, dims = 1)
colSums(x, dims = 2)

chevron_right


Output:

,, 1

     [, 1] [, 2] [, 3]
[1, ]    1    3    5
[2, ]    2    4    6,, 2

     [, 1] [, 2] [, 3]
[1, ]    7    9   11
[2, ]    8   10   12,, 3

     [, 1] [, 2] [, 3]
[1, ]    1    3    5
[2, ]    2    4    6

     [, 1] [, 2] [, 3]
[1, ]    3   15    3
[2, ]    7   19    7
[3, ]   11   23   11

[1] 21 57 21
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.