Open In App

Sum of Two or Multiple DataFrame Columns in R

Improve
Improve
Like Article
Like
Save
Share
Report

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

Database in use:

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.

Syntax:

dataframe$column1 + dataframe$column2

where

  • dataframe is the input dataframe
  • column1 is one column in the dataframe
  • column2 is another column in the dataframe

Example: R program to add two columns in dataframe

R




# 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 and column2
print(data$sub1 + data$sub2)
  
# add column1 and column3
print(data$sub1 + data$sub3)
  
# add column1 and column4
print(data$sub1 + data$sub4)
  
# add column2 and column4
print(data$sub2 + data$sub4)


Output:

[1] 190 179 164 173
[1] 179 179 176 188
[1] 176 167 165 188
[1] 186 168 173 183

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


Last Updated : 23 Sep, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads