How do you use dot referencing (for the data frame) and groups in dplyr?

Viewed 269

Consider the following example data:

tmp_df_dplyr <- data.frame(groups = rep(c("C", "B", "A"), each = 3), 
                           a = c(-2, 0, -1, -1, 0, 1, 0, 1, 2), 
                           b = rep(c(-1, 0, 1), each = 3))

I wish to do the following, except using colSums:

tmp_df_dplyr %>%
    group_by(groups) %>%
    summarise(min_group = min(c(sum(a), sum(b))))
# produces:
# A tibble: 3 × 2
  groups min_group
  <fctr>     <dbl>
1      A         3
2      B         0
3      C        -3

Using dot referencing, I get an unexpected result:

tmp_df_dplyr %>%
    group_by(groups) %>%
    summarise(min_group = min(colSums(.[, c('a', 'b')])))
# produces
# A tibble: 3 × 2
  groups min_group
  <fctr>     <dbl>
1      A         0
2      B         0
3      C         0

that is, it looks like the groups are not being applied.

0 Answers
Related