Calculate Sum of Two Data Frame Variables in R (2 Examples)

This tutorial shows how to compute the sum across two or more columns of a data frame in the R programming language.

Creation of Example Data

my_df <- data.frame(col1 = 1:5,             # Construct data frame
                    col2 = 2)
my_df                                       # Show data frame in RStudio console
#   col1 col2
# 1    1    2
# 2    2    2
# 3    3    2
# 4    4    2
# 5    5    2

Example 1: Computing Sum of 2 Columns

my_df$col1 + my_df$col2                     # Compute sum of 2 columns
# [1] 3 4 5 6 7

Example 2: Adding Sum of 2 Columns as New Variable to Data Frame

my_df$col_sum <- my_df$col1 + my_df$col2    # Add sum as variable to data
my_df                                       # Print updated data frame
#   col1 col2 col_sum
# 1    1    2       3
# 2    2    2       4
# 3    3    2       5
# 4    4    2       6
# 5    5    2       7

Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top