r - dplyr::group_by_ with character string input of several variable names -
i'm writing function user asked define 1 or more grouping variables in function call. data grouped using dplyr , works expected if there 1 grouping variable, haven't figured out how multiple grouping variables.
example:
x <- c("cyl") y <- c("cyl", "gear") dots <- list(~cyl, ~gear)  library(dplyr) library(lazyeval)   mtcars %>% group_by_(x)             # groups cyl mtcars %>% group_by_(y)             # groups cyl (not gear) mtcars %>% group_by_(.dots = dots)  # groups cyl , gear, want.   i tried turn y same dots using:
mtcars %>% group_by_(.dots = interp(~var, var = list(y))) #error: is.call(expr) || is.name(expr) || is.atomic(expr) not true   how use user-defined input string of > 1 variable names (like y in example) group data using dplyr?
(this question somehow related this one not answered there.)
no need interp here, use as.formula convert strings formulas:
dots = sapply(y, . %>% {as.formula(paste0('~', .))}) mtcars %>% group_by_(.dots = dots)   the reason why interp approach doesn’t work expression gives following:
~list(c("cyl", "gear"))   – not want. could, of course, sapply interp on y, similar using as.formula above:
dots1 = sapply(y, . %>% {interp(~var, var = .)})   but, in fact, can directly pass y:
mtcars %>% group_by_(.dots = y)   the dplyr vignette on non-standard evaluation goes more detail , explains difference between these approaches.
Comments
Post a Comment