Different output between sum and +

Viewed 56

I'm working on a problem that consists basically on sum all the rows based on their ID and sum some specific variables to get a consolidated dataset to input on another work, but there is an issue with the sum function and I'd appreciate some explanation about this.

Dataset:

teste <- data.frame(ID = c(1, 1, 2, 1, 3, 3, 2),
                    VALUE = c(10, 10, 10, 10, 10, 10, 10),
                    MOD = c(1, 1, 1, 1, 1, 1, 1))

  ID VALUE MOD
1  1    10   1
2  1    10   1
3  2    10   1
4  1    10   1
5  3    10   1
6  3    10   1
7  2    10   1

Using + operator:

teste %>%
    group_by(ID) %>%
    summarise_all(sum, na.rm = TRUE) %>%
    mutate(CONS = VALUE + MOD)

# A tibble: 3 x 4
     ID VALUE   MOD  CONS
  <dbl> <dbl> <dbl> <dbl>
1     1    30     3    33
2     2    20     2    22
3     3    20     2    22

Using sum function:

teste %>%
    group_by(ID) %>%
    summarise_all(sum, na.rm = TRUE) %>%
    mutate(CONS = sum(VALUE, MOD))

# A tibble: 3 x 4
     ID VALUE   MOD  CONS
  <dbl> <dbl> <dbl> <dbl>
1     1    30     3    77
2     2    20     2    77
3     3    20     2    77
1 Answers

summarize_all removes one level of grouping so re-group it:

teste %>%
    group_by(ID) %>%
    summarise_all(sum, na.rm = TRUE) %>%
    group_by(ID) %>%   # <--------------------------
    mutate(CONS = sum(VALUE, MOD)) %>%
    ungroup

giving:

# A tibble: 3 x 4
# Groups:   ID [3]
     ID VALUE   MOD  CONS
  <dbl> <dbl> <dbl> <dbl>
1     1    30     3    33
2     2    20     2    22
3     3    20     2    22
Related