Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
491 views
in Technique[技术] by (71.8m points)

r - dplyr::group_by_ with character string input of several variable names

I'm writing a function where the user is asked to define one or more grouping variables in the function call. The data is then grouped using dplyr and it works as expected if there is only one grouping variable, but I haven't figured out how to do it with multiple grouping variables.

Example:

x <- c("cyl")
y <- c("cyl", "gear")
dots <- list(~cyl, ~gear)

library(dplyr)
library(lazyeval) 

mtcars %>% group_by_(x)             # groups by cyl
mtcars %>% group_by_(y)             # groups only by cyl (not gear)
mtcars %>% group_by_(.dots = dots)  # groups by cyl and gear, this is what I want.

I tried to turn y into the same as dots using:

mtcars %>% group_by_(.dots = interp(~var, var = list(y)))
#Error: is.call(expr) || is.name(expr) || is.atomic(expr) is not TRUE

How to use a user-defined input string of > 1 variable names (like y in the example) to group the data using dplyr?

(This question is somehow related to this one but not answered there.)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No need for interp here, just use as.formula to convert the strings to formulas:

dots = sapply(y, . %>% {as.formula(paste0('~', .))})
mtcars %>% group_by_(.dots = dots)

The reason why your interp approach doesn’t work is that the expression gives you back the following:

~list(c("cyl", "gear"))

– not what you want. You could, of course, sapply interp over y, which would be similar to using as.formula above:

dots1 = sapply(y, . %>% {interp(~var, var = .)})

But, in fact, you can also directly pass y:

mtcars %>% group_by_(.dots = y)

The dplyr vignette on non-standard evaluation goes into more detail and explains the difference between these approaches.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...