Sum of Two or Multiple DataFrame Columns in R

• Last Updated : 23 Sep, 2021

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 marksdata=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 column2print(data\$sub1 + data\$sub2)  # add column1 and column3print(data\$sub1 + data\$sub3)  # add column1 and column4print(data\$sub1 + data\$sub4)  # add column2 and column4print(data\$sub2 + data\$sub4)

Output:

 190 179 164 173
 179 179 176 188
 176 167 165 188
 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 marksdata = 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 4print(rowSums(data[, c("sub1", "sub2", "sub4")]))  # add column1, column2 and column 3print(rowSums(data[, c("sub1", "sub2", "sub3")]))  # add column4, column2 and column 3print(rowSums(data[, c("sub4", "sub2", "sub3")]))

Output:

 276 257 251 272
 279 269 262 272
 275 258 271 282

My Personal Notes arrow_drop_up