Sum of multiple columns

We can calculate the sum of multiple columns by using rowSums() and c() Function. we simply have to pass the name of the columns.

Syntax:

rowSums(dataframe[ , c(“column1”, “column2”, “column n”)])

where

  • dataframe is the input dataframe
  • c() represents the number of columns to be specified to add

Example: R program to add multiple columns

Python3




# create a dataframe with subjects marks
data = data.frame(sub1=c(90, 89, 78, 89), 
                  sub2=c(100, 90, 86, 84), 
                  sub3=c(89, 90, 98, 99),
                  sub4=c(86, 78, 87, 99))
  
# add column1, column2 and column 4
print(rowSums(data[, c("sub1", "sub2", "sub4")]))
  
# add column1, column2 and column 3
print(rowSums(data[, c("sub1", "sub2", "sub3")]))
  
# add column4, column2 and column 3
print(rowSums(data[, c("sub4", "sub2", "sub3")]))


Output:

[1] 276 257 251 272
[1] 279 269 262 272
[1] 275 258 271 282


Sum of Two or Multiple DataFrame Columns in R

In this article, we will discuss how to perform some of two and multiple dataframes columns in R programming language.

Database in use:

Similar Reads

Sum of two columns

The columns whose sum has to be calculated can be called through the $ operator and then we can perform the sum of two dataframe columns by using “+” operator....

Sum of multiple columns

...