2

I want to be able to enter a column name of a tibble in a user function with or without using quotation marks. Using myfunc function below I can enter the column name, but I can't encapsulate it within "". Is there a way to use both methods in a single user-defined function?

myfunc <- function(dat, col1){
  dat %>%
    mutate(col2 = {{ col1 }}+1)
}
# ok
myfunc(iris, Sepal.Length)

# error
myfunc(iris, "Sepal.Length")

aynber
  • 22,380
  • 8
  • 50
  • 63
Andrew
  • 111
  • 4

1 Answers1

1

You can use as.name and substitute to convert your character variable to an unquoted variable, and at the same time not change a variable that is already unquoted:

myfunc <- function(dat, col1){
  col1 <- as.name(substitute(col1))
  dat %>%
    mutate(col2 = {{col1}} + 1)
}

output

all.equal(myfunc(iris, Sepal.Length), 
          myfunc(iris, "Sepal.Length"))
#[1] TRUE
Maël
  • 45,206
  • 3
  • 29
  • 67
  • Great. thanks for that Mael. Any idea how to handle more than 1 column at a time? I tried using map_df(c("Sepal.Length", "Sepal.Width"), ~myfunc(iris, .x)) but an error occurred "Error in `mutate()`: ! Problem while computing `col2 = .x + 1`. Caused by error: ! object '.x' not found" – Andrew Sep 21 '22 at 13:33