I am trying to allow a user to enter a version of cut_
, and use the version of the function that they've specified in a mutate
function downstream.
A functioning version of the code to make a cut is found below:
df2<- d3 %>%
mutate_if(is.numeric,funs(cut_interval(.,n=5)))
What I'd like to do from here, instead of having cut_interval()
included in my code explicitly, is to allow a user to enter a value for a variable named "slicer". If the value they enter is "cut_interval", then I'd like the mutate function to use that. If they entered "cut_number", then I'd like that cut function to be applied instead.
My non-working attempts at this are:
slicer <- "cut_number"
ifelse(slicer=="cut_number",
df2<- d3 %>%
mutate_if(is.numeric,funs(cut_number(.,n=5))),
df2<- d3 %>%
mutate_if(is.numeric,funs(cut_interval(.,n=5))))
and
df2<- d3 %>%
mutate_if(is.numeric,funs(paste0(slicer,"(.,n=5)")))
Thank you in advance for any help!
Note: Changing to if/else, per the recommendation by @akrun in the comment below, the follow code works:
if (slicer=="cut_number"){
df2<- d3 %>%
mutate_if(is.numeric,funs(cut_number(.,n=5)))} else {df2<- d3 %>%
mutate_if(is.numeric,funs(cut_interval(.,n=5)))}
Expanding on the original purpose, imagine a situation where there were hundreds of various functions that I may want to allow a user to type as a value for slicer
and would like that the function in applied. Is there a method to scale in this manner?