0

I am writing a function using case_when as exampled below:

library(tidyverse)

#what I want to happen
iris%>%
mutate(category=case_when(Petal.Length<1.5~"less than 1.5", 
                          TRUE~"other"))

#the function version
fn<-function(df, column){
df%>%
mutate(category=case_when(column<1.5~"less than 1.5", 
                                  TRUE~"other"))       
}

#trying to run the function
fn(iris, Petal.Length)

When I run the function I get the error message object 'Petal.Length' not found . Can anyone ammend the function so I can pass the name of the column into it?

Basil
  • 747
  • 7
  • 18
  • The answer is to use {{ }} brackets: fn<-function(df, column){ df%>% mutate(category=case_when({{column}}<1.5~"less than 1.5", TRUE~"other")) } – Basil Jul 13 '23 at 09:38

0 Answers0