2

I realize this seems close to other questions already asked and it seems answered on https://cran.r-project.org/web/packages/dplyr/vignettes/programming.html but what I show below seems to follow that advise but without success. Here is the data:

 d<-tibble(y=c(1,2,3,NA))

First something that works:

my.f <- function(df,column_var){
  df %>%
  mutate(z = y) %>%
  filter(!is.na(z))
}
my.f(d,quo(z))

Now something that I want to produce the same result, but doesn't work:

my.f <- function(df,column_var){
  df %>%
  mutate(!!column_var = y) %>%
  filter(!is.na(!!column_var))
}
my.f(d,quo(z))

Error: unexpected '=' in:
"  df %>%
mutate(!!column_var ="
0

1 Answer 1

4

For setting variable names you'll need a string on the left hand side and := instead of = in mutate.

You can use quo_name for turning z into a string for the column name.

Your function could then look like:

my.f = function(df, column_var) {
     column_var = enquo(column_var)

     df %>%
       mutate(!!quo_name(column_var) := y) %>%
       filter( !is.na(!!column_var) )
}

my.f(d, z)

# A tibble: 3 x 2
      y     z
  <dbl> <dbl>
1     1     1
2     2     2
3     3     3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.