Open In App

Sum of rows in R based on condition

Last Updated : 21 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

To find the sum of rows in R based on a condition, we select only the rows that match the condition and then use the sum() function to add their values.

Method 1: Sum of Rows Based on a Single Condition

We calculate the sum of specific row values filtered by one logical condition.

Example: 1

  • team, captain, centuries: vectors used to define data
  • data.frame(): creates the data frame from vectors
  • df: name of the data frame
  • print(): displays the data frame or result
  • with(): applies expressions within a data frame context
  • sum(): calculates the total
  • [captain == 'dhoni']: filters rows where captain equals "dhoni"
R
team=c("csk", "rcb","kxip","csk","gt","rcb")
captain=c("dhoni","kohli","rahul","dhoni","hardik","kohli")
centuries=c(70,64,50,70,35,43)

df = data.frame(team,captain,centuries)
print(df)

print("Sum of rows based on the single condition")
with(df, sum(centuries[captain == 'dhoni']))

Output:

team_captain
Output

Example: 2

  • name, age, place: vectors used to define the data
  • df: name of the data frame
  • place == "guntur": filters rows where the place equals "guntur"
  • sum(age[...]): sums the age values matching the condition
R
df = data.frame(name=c("rakesh", "ravi","mahesh","pavan","satish", "naresh"),
               age=c(12:17),
               place=c("nellore","palanadu","guntur","guntur","palanadu"," prakasam"))

print(df)

print("Sum of rows based on the single condition")
with(df, sum(age[place == "guntur"]))

Output:

data_frame
Output

Method 2: Sum of Rows Based on Multiple Conditions

We calculate the sum by applying multiple logical filters simultaneously.

Example: 1

  • employee, emp_id, salary: columns in the data frame
  • emp_id > 7: filters rows with emp_id greater than 7
  • employee == 'x': filters rows where employee is "x"
  • &: logical AND operator to combine conditions
  • sum(...): computes total for matching rows
R
df = data.frame(employee = c("x", "y","y","w", "x","z","z"),
                 emp_id = c(4, 7, 7, 4,15, 12, 12),
                 salary = c(30000, 45000, 25000, 40000, 60000, 70000, 55000))

print(df)

print("Sum of rows based on the multiple conditions")
with(df, sum(salary[emp_id > 7 & employee== 'x']))

Output:

salary
Output

Example: 2

  • vec1, vec2, vec3: vectors used to create the data frame
  • vec2 == "a" & vec3 == "pk": compound condition for filtering rows
  • sum(vec1[...]): computes the total of vec1 where both conditions are met
R
vec1=c(4,4,6,7,8,8,9)
vec2=c("a","a","c","e","e","f","g")
vec3=c("pk","pk","sk","pk","mk","ak","kk")

df = data.frame(vec1, vec2, vec3)

print(df)

print("Sum of rows based on the multiple conditions")
with(df, sum(vec1[vec2 == "a" &  vec3== "pk"]))

Output:

dataset
Output

We learned how to calculate the sum of rows based on conditions in R programming language.


Similar Reads