What is the colSums() Function in R

The colSums() function in R is “used to calculate the sum of each column in a data frame or matrix”.

Syntax

colSums(x, na.rm = FALSE)

Parameters

  1. x: It is an array of two or more dimensions containing numeric, complex, integer, or logical values or a numeric data frame.
  2. na.rm: It is logical. Should missing values (including NaN) be omitted from the calculations?

Example 1: Use colSums() with Data Frame

df <- data.frame(
  run1 = c(11, 31, 23, 24, 52),
  run2 = c(19, 21, 25, 32, 22),
  run3 = c(21, 31, 62, 62, 82),
  run4 = c(18, 11, 22, 14, 29)
)

colSums(df)

Output

 run1  run2  run3  run4
  141  119   258    94

Example 2: Use the colSums() function with NA Values in Data Frame

You can exclude NA values from the data frame by passing the na.rm = TRUE parameter to the colSums() function.

df <- data.frame(
  run1 = c(11, 31, NA, 24, 52),
  run2 = c(19, 21, 25, NA, 22),
  run3 = c(21, NA, 62, 62, 82),
  run4 = c(NA, 11, 22, 14, 29)
)

colSums(df, na.rm = TRUE)

Output

 run1  run2  run3  run4
 118    87    227   76

Example 3: Use colSums() with specific columns

You can use the colSums() function to find the sum of the specific columns of a data frame.

df <- data.frame(
  run1 = c(11, 31, 23, 24, 52),
  run2 = c(19, 21, 25, 32, 22),
  run3 = c(21, 31, 62, 62, 82),
  run4 = c(18, 11, 22, 14, 29)
)

colSums(df[, c(2, 4)])

Output

 run2  run4
  119   94

Example 4: Use the colSums() function on Matrix

You can use the colSums() function to calculate the sum of column values of the matrix.

mtrx <- matrix(rep(1:4), 2, 2)
mtrx
cat("The sum of columns is: ", "\n")
colSums(mtrx)

Output

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

The sum of columns is:

[1] 3 7

Example 5: Calculating the sum of column values in Data Set

You can use the inbuilt R dataset like ChickWeight and calculate the sum of its column values. But first, let’s get the snapshot of the ChickWeight dataset using the head() function.

head(USArrests, 5)

Output

          Murder Assault UrbanPop  Rape
Alabama    13.2    236     58      21.2
Alaska     10.0    263     48      44.5
Arizona     8.1    294     80      31.0
Arkansas    8.8    190     50      19.5
California  9.0    276     91      40.6

We will use the colSums() function to calculate the sum of Murder, Assult, UrbanPop, and Rape column values.

colSums(USArrests)

Output

Murder  Assault  UrbanPop   Rape
389.4   8538.0    3277.0   1061.6

That’s it.

Related posts

rowMeans() in R

rowSums() in R

colMeans() in R

Leave a Comment