group_by_ with paste0, then summarise

For some reason when I try to use paste as part of a group_by_ only one of the two elements in the vector that the paste creates gets used as a group_by_ for the summarising on the next line. Is there any way to keep both the "gear_CI" and the "carb_CI" columns? (I realize the purpose of why I'm trying to group_by might not make a lot of sense in this context, but this is just meant to be a reproducible example)

somecols <- c("gear", "carb")
mtcars %>%
  mutate_at(vars(somecols), funs(CI = qnorm(.975) * .)) %>%
  group_by_("wt", paste0(somecols, "_CI")) %>%
  summarise_at(vars(somecols), mean)

# A tibble: 31 x 4
# Groups:   wt [29]
#      wt gear_CI  gear  carb
#   <dbl>   <dbl> <dbl> <dbl>
# 1  1.51    9.80     5     2
# 2  1.62    7.84     4     2
# 3  1.84    7.84     4     1
# 4  1.94    7.84     4     1

I think this is not working because group_by_() doesn't take vectors as arguments and you are passing ... = "wt", c("gear_CI", "carb_CI"), you could use group_by_at instead.

library(dplyr)
somecols <- c("gear", "carb")
mtcars %>%
    mutate_at(vars(somecols), list(CI = ~qnorm(.975) * .)) %>%
    group_by_at(vars("wt", paste0(somecols, "_CI"))) %>%
    summarise_at(vars(somecols), mean)
#> # A tibble: 31 x 5
#> # Groups:   wt, gear_CI [31]
#>       wt gear_CI carb_CI  gear  carb
#>    <dbl>   <dbl>   <dbl> <dbl> <dbl>
#>  1  1.51    9.80    3.92     5     2
#>  2  1.62    7.84    3.92     4     2
#>  3  1.84    7.84    1.96     4     1
#>  4  1.94    7.84    1.96     4     1
#>  5  2.14    9.80    3.92     5     2
#>  6  2.2     7.84    1.96     4     1
#>  7  2.32    7.84    1.96     4     1
#>  8  2.46    5.88    1.96     3     1
#>  9  2.62    7.84    7.84     4     4
#> 10  2.77    9.80   11.8      5     6
#> # … with 21 more rows

Created on 2019-04-15 by the reprex package (v0.2.1.9000)

5 Likes

yup that did the trick. hmm i was not familiar with group_by_at, but that makes perfect sense. thanks so much!!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.