R user function column name selection with or without quotes

Viewed 18

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")

1 Answers

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
Related