Sum cells in rows based on certain value in another column

This is one way to do it

library(dplyr)

# This is your sample data on a copy/paste friendly format
sample_df <- data.frame(
  stringsAsFactors = FALSE,
                X1 = c("a", "b", "a", "c", "c"),
                X2 = c(1, 5, 3, 6, 2),
                X3 = c(3, 3, 4, 5, 2)
)

sample_df %>% 
    group_by(X1) %>% 
    summarise_all(sum)
#> # A tibble: 3 x 3
#>   X1       X2    X3
#>   <chr> <dbl> <dbl>
#> 1 a         4     7
#> 2 b         5     3
#> 3 c         8     7

Created on 2020-04-09 by the reprex package (v0.3.0.9001)

Next time, please provide a proper REPRoducible EXample (reprex) illustrating your issue.

2 Likes