VOOZH about

URL: https://www.geeksforgeeks.org/r-language/sum-of-rows-in-r-based-on-condition/

⇱ Sum of rows in R based on condition - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sum of rows in R based on condition

Last Updated : 21 Jul, 2025

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"

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

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

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

Output:

👁 dataset
Output

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

Comment

Explore