So I have this code that will be part of an application (the application will allow you to import a data frame and apply different functions to it).
#create a list of functions
choose_functions <- function(...){
rlang::enexprs(...)
}
#apply the list of functions to a data frame
apply_functions <- function(df, functions_list) {
for (i in seq_along(functions_list)) {
fn <- functions_list[[i]]
tryCatch(
{
df <- eval_tidy(fn)
},
error = function(e) {
message(paste("Error in filter", i, ":", conditionMessage(e), "\n"))
return(NULL)
},
warning = function(e) {
message(paste("This filter caused a warning", i, ":", conditionMessage(e), "\n"))
return(NULL)
}
)
}
return(df)
}
To create the list of functions, you do something like this:
l1<- choose_functions(replace(df, df =="a" , "b"),
filter(df, x==10),
replace(df, df =="d" , "e"))
If I pass l1 like argument to my function apply_function(), everitihing works well.
The thing is that I would like the app user to be able to write the functions they want to apply, in this way:
l1<- choose_functions(replace("a" , "b"),
filter(x==10),
replace("d" , "e"))
I have tried:
apply_functions <- function(df, functions_list) {
for (i in seq_along(functions_list)) {
fn <- functions_list[[i]]
tryCatch(
{
df <- df %>% eval_tidy(fn)
#or
df <- eval_tidy(fn, data=df)
#or
df<-eval_tidy(fn, data=list(.data[[df]]))
},
error = function(e) {
message(paste("Error in filter", i, ":", conditionMessage(e), "\n"))
return(NULL)
},
warning = function(e) {
message(paste("This filter caused a warning", i, ":", conditionMessage(e), "\n"))
return(NULL)
}
)
}
return(df)
}
I also tried to rewrite the code to work with rlang::exec(), I also tried to make lists with the names of the functions and lists with the arguments, nothing worked.
Thanks