Row wise mean – row mean in R dataframe

Row wise mean of the dataframe in R is calculated using rowMeans() function. Other method to get the row mean in R is by using apply() function.

  • Row wise mean of r dataframe using rowMeans()
  • Row mean of the dataframe using apply() function.

First let’s create the dataframe


df1 = data.frame( Name = c('George','Andrea', 'Micheal','Maggie','Ravi','Xien','Jalpa'), 
 Mathematics1_score=c(62,47,55,74,32,77,86),
 Mathematics2_score=c(45,78,44,89,66,49,72),
 Science_score=c(56,52,45,88,33,90,47))

df1 will be

Row wise mean in R dataframe Row mean in R 1

 

 

Row wise mean in R dataframe using rowMeans() :

Let’s calculate the row wise mean in R using rowMeans() function as shown below

## row wise mean using rowMeans()

df1$Avg_score = rowMeans(df1[,c(2,3,4)])
df1

or

 
## row wise mean using rowMeans()

df1$Avg_score = rowMeans(df1[,c(-1)])
df1

So the resultant dataframe will be

Row wise mean in R dataframe Row mean in R 2

 

 

Row wise mean in R dataframe using apply() function:

Let’s calculate the row wise mean in R using apply() function as shown below

 

### Row wise mean using apply() function

df1$Avg_score = apply(df1[,-1], 1, mean)
df1

So the resultant dataframe will be

Row wise mean – row mean in R dataframe 3