Search code examples
rdataframegroup-bysumtidyr

r - Collapse multiple rows in one following multiple conditions with tidyr


i have a database structure like this

 A   B   C 
 n   1   M
 n   2   U
 n   1   U
 f   3   M
 f   4   M
 f   1   U

using the package tidyr, I want to obtain this result:

 A   B   C
 n   1   M
 n   3   U
 f   7   M
 f   1   U

So I want to make a sum of the b value characterized by the same A value and, obtained this sub set, collapsing B value in relation to the same C value.

How could I do?


Solution

  • library(dplyr)
    df %>% 
      group_by(A,C) %>%
      summarize(B=sum(B)) %>%
      data.frame()