How to Use colMeans() Function in R


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

This function uses the following basic syntax:

#calculate column means of every column
colMeans(df)

#calculate column means and exclude NA values
colMeans(df, na.rm=T)

#calculate column means of specific columns
colMeans(df[c('col1', 'col3', 'col4')])

The following examples show how to use this syntax in practice.

Example 1: Calculate Mean of Every Column

The following code shows how to calculate the mean of every column in a data frame:

#create data frame
df <- data.frame(points=c(99, 91, 86, 88, 95),
                 assists=c(33, 28, 31, 39, 34),
                 rebounds=c(30, 28, 24, 24, 28),
                 blocks=c(1, 4, 11, 0, 2))

#calculate column means
colMeans(df)

  points  assists rebounds   blocks 
    91.8     33.0     26.8      3.6 

Example 2: Calculate Mean of Every Column & Exclude NA’s

The following code shows how to calculate the mean of every column and exclude NA values:

#create data frame with some NA values
df <- data.frame(points=c(99, 91, 86, 88, 95),
                 assists=c(33, NA, 31, 39, 34),
                 rebounds=c(30, 28, NA, NA, 28),
                 blocks=c(1, 4, 11, 0, 2))

#calculate column means
colMeans(df, na.rm=T)

  points  assists rebounds   blocks 
91.80000 34.25000 28.66667  3.60000

Example 3: Calculate Mean of Specific Columns

The following code shows how to calculate the mean values of specific columns in the data frame:

#create data frame
df <- data.frame(points=c(99, 91, 86, 88, 95),
                 assists=c(33, 28, 31, 39, 34),
                 rebounds=c(30, 28, 24, 24, 28),
                 blocks=c(1, 4, 11, 0, 2))

#calculate column means for 'points' and 'blocks' columns
colMeans(df[c('points', 'blocks')])

points blocks 
  91.8    3.6 

Note that we can also use index values to calculate the mean of specific columns:

#create data frame
df <- data.frame(points=c(99, 91, 86, 88, 95),
                 assists=c(33, 28, 31, 39, 34),
                 rebounds=c(30, 28, 24, 24, 28),
                 blocks=c(1, 4, 11, 0, 2))

#calculate column means for columns in position 1 and 4
colMeans(df[c(1, 4)])

points blocks 
  91.8    3.6 

Additional Resources

The following tutorials explain how to perform other common functions in R:

How to Calculate Standard Deviation of Columns in R
How to Calculate the Mean by Group in R
How to Calculate the Sum by Group in R

Leave a Reply

Your email address will not be published.