Calculate mean of specific columns

In this method, the user has an option to get the mean of the specific column of the given data frame either to get the mean of the complete data frame using the colmean() function with the name of the specific column within it for which mean is to be calculated in the R language.

Syntax:

colMeans(dataframe)

where,

  • dataframe is the input dataframe
  • columns are the columns to get mean

Example:

In this example, we will be using the colmean() function with the name of the column as its argument to get the mean of that particular column of the data frame in the R language.

R




# create  dataframe with three columns
data=data.frame(col1=c(1,34,56,32,23),
                col2=c(21,34,56,32,34),
                col3=c(1:5))
 
# get mean of col2 and col3
print(colMeans(data[c('col2', 'col3')]))


Output:

col2 col3 
35.4  3.0 

Here, we can also use column numbers to get the mean value using colMeans().

Syntax

colMeans(dataframe)

where

  • col_value_start is the first column index
  • col_value_end is the last column index

Example:

R




# create  dataframe with three columns
data=data.frame(col1=c(1,34,56,32,23),
                col2=c(21,34,56,32,34),
                col3=c(1:5))
 
# get mean from column1 to column3
print(colMeans(data[c(1,3)]))


Output:

col1 col3 
29.2  3.0 

How to Use ColMeans Function in R?

In this article, we will discuss how to use the ColMeans function in R Programming Language.

Similar Reads

Using colmeans() function

The colmean() function call be simply called by passing the parameter as the data frame to get the mean of every column present in the data frame separately in the R language....

Calculate mean of specific columns

...

Calculate the mean of every column & exclude NA’s

In this method, the user has an option to get the mean of the specific column of the given data frame either to get the mean of the complete data frame using the colmean() function with the name of the specific column within it for which mean is to be calculated in the R language....

Calculate the mean of columns of the array in R

...

Contact Us