r-lib / rlang

Low-level API for programming with R
https://rlang.r-lib.org
Other
501 stars 137 forks source link

Sending vectors to function #630

Closed marinsokol5 closed 5 years ago

marinsokol5 commented 5 years ago

Hi I just can't seem to get something to work and although I do know that this is not the right place for posting this, it is the easiest way to get response from you, rlang developers.

It is an really easy example.

rm(list = ls())
library(rlang)

df <- data.frame(
  a = c(1, 2),
  b = c(2, 3),
  d = c(3, 4)
)

# I am sending df to a function which will have to do dplyr::group first by (a,b) and then by (b,d) 
# so I need two vectors of quosures.
# Dplyr library provides an easy way of doing it when there is only one group of them. You just
# send columns to a function that takes ... (three dot elipsis) and then do quos(...), but what if I need 2 (or more) groups.

# One option would be to try and put those column in a vector.
f <- function(df, group1, group2) {
  print(enquos(group1))
}
df %>% f(c(a,b), c(b, d))
# Quosure is created in shape of ^c(a, b) which makes sense as that expression is evaluated.

Is there any way of doing this without some hacking. By hacking I mean, turning c(a,b) to a string and then removing "c(" and ")" and splitting by "," and then turning all of that to quosure vector by quos(!!! syms(group))

Thanks in advance.

All the best.

lionel- commented 5 years ago

I just can't seem to get something to work and although I do know that this is not the right place for posting this, it is the easiest way to get response from you, rlang developers.

I recommend posting questions on Stackoverflow or community.rstudio.com.

You're right that capturing inputs and looking for c() is not the right way. I think you're looking for external quoting. You can require your users to pass variables with dplyr::vars(). It is a simple alias to quos() with a friendlier name.

f <- function(df, group1) {
  stopifnot(is_list(group1))
  dplyr::group_by(df, !!!group1)
}
f(mtcars, vars(cyl, am))

See https://tidyeval.tidyverse.org/dplyr.html#vars---quote-multiple-arguments-externally

lionel- commented 5 years ago

I recommend posting questions on Stackoverflow or community.rstudio.com.

This way the answer benefits to other users.