Mean of a column in R can be calculated by using mean() function. Mean() Function takes column name as argument and calculates the mean value of that column. Mean of single column in R, Mean of multiple columns in R using dplyr. Get row wise mean in R. Let’s see how to calculate Mean in R with an example
- Mean of the single column in R – mean() function
- Mean of multiple columns in R
- Mean of Multiple columns in R using dplyr
- Find Mean of the column by column name
- Find Mean of the column by column position
- Get Row wise mean in R
- Populate mean of a column in the new column
Let’s first create the dataframe.
### Create Data Frame df1 = data.frame(Name = c('George','Andrea', 'Micheal','Maggie','Ravi','Xien','Jalpa'), Grade_score=c(4,6,2,9,5,7,8), Mathematics1_score=c(45,78,44,89,66,49,72), Science_score=c(56,52,45,88,33,90,47)) df1
So the resultant dataframe will be
Get Mean of the column in R : Mean of the columns by its name
Method 1: Get Mean of the column by column name
# Get Mean of the column by column name mean(df1$Mathematics1_score)
Result:
Get Mean of the column in R: Mean of the columns by position
Method 2: Get Mean of the column by column position
# Get Mean of the column by column position mean(df1[,3])
Result:
Get Mean of multiple columns R using colMeans() : Method 1
ColMeans() Function along with sapply() is used to get the mean of the multiple column. Dataframe is passed as an argument to ColMeans() Function. Mean of numeric columns of the dataframe is calculated.
# Get Mean of the multiple columns colMeans(df1[sapply(df1, is.numeric)])
Mean of numeric columns of the dataframe will be
Get Mean of multiple columns using Dplyr : Method 2
summarise_if() Function along with is.numeric is used to get the mean of the multiple column . With the help of summarise_if() Function, Mean of numeric columns of the dataframe is calculated.
# Get Mean of the multiple columns using dplyr library(dplyr) df1 %>% summarise_if(is.numeric, mean)
Mean of numeric columns of the dataframe will be
Get Row wise mean in R
Let’s calculate the row wise mean of mathematics1_score and science_score as shown below.using rowMeans() function which takes matrix as input. so the dataframe is converted to matrix using as.matrix() function.
# Get Row wise mean in R df1$Avg_score = rowMeans(df1[,c(3,4)]) df1
so the resultant dataframe with row wise mean calculated will be
Populate Mean of the column in a new column:
Lets populate Mean of the column “Mathematics1_score” in the new column named “Mathematics_mean
df1$Mathematics_mean= mean(df1$Mathematics1_score) df1
OR
df1$Mathematics_mean= mean(df1[,3]) df1
Output:
Other Related Topics: