What is the colMeans() Function in R

The colMeans() function in R is “used to calculate the mean of several columns of a data frame or matrix”.

Syntax

colMeans(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 a logical argument. If TRUE, NA values are ignored.

Return value

The colMeans() function returns the mean of the columns of a data frame or matrix.

Example 1: Calculating the mean of every column in a data frame

Syntax

colMeans(df)

You can calculate the mean of every data frame column using the colMeans() function in R.

# Create data frame
df <- data.frame(
  player1 = c(11, 55, 99, 444, 888),
  player2 = c(22, 66, 111, 555, 999),
  player3 = c(33, 77, 222, 666, 11),
  player4 = c(44, 88, 333, 777, 22)
)

# Calculate column means
colMeans(df)

Output

player1 player2  player3  player4
 299.4   350.6   201.8   252.8

Example 2: Calculating the mean of every column and Exclude NA values

Syntax

colMeans(dataframe,na.rm=TRUE)

You can calculate the mean of every column, excluding NA values in R, using the colMeans() function.

# Create data frame
df <- data.frame(
  player1 = c(11, 55, 99, NA, 888),
  player2 = c(22, 66, 111, 555, 999),
  player3 = c(33, 77, NA, 666, 11),
  player4 = c(44, 88, 333, 777, NA)
)

# Calculate column means
colMeans(df, na.rm = TRUE)

Output

 player1  player2  player3  player4
 263.25   350.60   196.75    310.50

Example 3: Calculating the mean of specific columns

Syntax

colMeans(df[c("col1", "col2")])

Let’s write code based on the above syntax.

# Create data frame
df <- data.frame(
  player1 = c(11, 55, 99, 444, 888),
  player2 = c(22, 66, 111, 555, 999),
  player3 = c(33, 77, 222, 666, 11),
  player4 = c(44, 88, 333, 777, 22)
)

# Calculate column means of "player2" and "player4"
colMeans(df[c("player2", "player4")])

Output

player2  player4 
 350.6    252.8

That’s it.

Related posts

rowMeans in R

rowSums in R

colSums in R

Leave a Comment