Row wise sum – row sum in R dataframe

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

  • Row wise sum of r dataframe using rowSums()
  • Row sum 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 sum in R dataframe Row sum in R 1

 

 

Row wise sum in R dataframe using rowSums()

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

## row wise sum using rowSums()

df1$row_sum = rowSums(df1[,c(2,3,4)])
df1

or


## row wise sum using rowSums()

df1$row_sum = rowSums(df1[,c(-1)])
df1

so the resultant dataframe will be

Row wise sum – row sum in R dataframe 2

 

 

Row wise sum  in R dataframe using apply() function

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


### Row wise sum using apply() function

df1$row_sum = apply(df1[,-1], 1, sum)
df1

So the resultant dataframe will be

Row wise sum – row sum in R dataframe 3