I'm looking for a way to concatenate a quosure and a string whose result is a quosure. Actually, if I use paste0() and quo_name(), I can do it. But I wonder if there is a more elegant alternative to write a function in my package. This is a generic example:
library(dplyr)
df <- data_frame(
z_1 = 1,
z_2 = 2,
y_1 = 10,
y_2 = 20
)
get_var <- function(.data, var) {
xx = enquo(var)
select(.data, paste0(quo_name(xx), "_1"), paste0(quo_name(xx), "_2"))
}
get_var(df, z)
# A tibble: 1 x 2
z_1 z_2
<dbl> <dbl>
1 1 2
Without a function, this is how you do it using
dplyr:You can also create a function and pass in a string for the variable name like this:
Now, the tricky part comes when you are trying to pass in the variable name without quoting it into a function (the R code, not the value it contains). One way of doing it would be
deparse+substitutein Base R. This converts the symbol supplied tovarto a string, which is convenient for later use within the function:Finally, here is how to do the same with
enquoandquo_nameinrlang/tidyversepackage:Result:
Notes:
enquotakes a symbol referring to a function's argument, quotes the R code and bundles it with the function's environment in a quosure.quo_nameformats a quosure into a string, which can be used later in the function.quo_textis similar toquo_namebut does not check for whether the input is a symbol.Check these:
rlangdocumentation?enquo?quo_name