Within a function, I want to update-in-place the values of columns specified by the user, where the user specified column names are captured via enquo(). So, here's a simplified example:
f1 <- function(df, x, y) {
x <- enquo(x)
y <- enquo(y)
df %>%
mutate((!! x) := (!! x)^2,
(!! y) := (!! y)+1)
}
dat <- data.frame(a=1:10, b=10:1)
f1(dat, x=a, y=b)
This fails with an error: "The LHS of :=
must be a string or a symbol".
I've also tried replacing, for example, (!! x)
with quo_get_expr(x)
and f_text(x)
, but get the same error. For example:
f1 <- function(df, x, y) {
x <- enquo(x)
y <- enquo(y)
df %>%
mutate(quo_get_expr(x) := (!! x)^2,
quo_get_expr(y) := (!! y)+1)
}
Can anyone point out what I'm doing wrong?
I'm using R 4.1, dplyr 0.7.4, and rlang 0.2.0
Thanks in advance.
You need to use quo_name
. This works:
f1 <- function(df, x, y) {
x <- enquo(x)
y <- enquo(y)
df %>%
mutate(
!!quo_name(x) := (!!x)^2,
!!quo_name(y) := (!!y)+1)
}
dat <- data.frame(a=1:10, b=10:1)
f1(dat, x=a, y=b)