I am looking to make a function where the user can enter their own model selection function as an input to be used. I'm having trouble with finding the answer as I keep getting search results about how to make a simple R function, as opposed to an input much like the apply family.
Here is an example similar to what I am looking for but not quite:
simple<- function(mod, FUN){
switch(FUN,
AIC = AIC(mod),
BIC = BIC(mod))
}
simple(lm(rnorm(100) ~ rnorm(100,4)), "AIC")
The above code runs but I must plan for all of the possible functions and write them within switch. I also am forced to write "AIC" as opposed to simply AIC.
Any thoughts to how I can create the function I am looking for? Let me know if you need additional information.
You can create an input function from an R data frame using the input_fn() method. You can specify feature and response variables either explicitly or using the R formula interface. Note that input_fn functions provide several parameters for controlling how data is drawn from the input source.
FUN is found by a call to match. fun and typically is specified as a function or a symbol (e.g., a backquoted name) or a character string specifying a function to be searched for from the environment of the call to lapply . Function FUN must be able to accept as input any of the elements of X .
Using readline() method In R language readline() method takes input in string format. If one inputs an integer then it is inputted as a string, lets say, one wants to input 255, then it will input as “255”, like a string.
Something like this:
simple<- function(mod, FUN){
FUN <- match.fun(FUN)
FUN(mod)
}
simple(lm(rnorm(100) ~ rnorm(100,4)),FUN = "BIC")
match.fun
accepts a function, symbol or character, so there is some flexibility in how the FUN
argument is passed.
An option for passing multiple functions, as mentioned in the comments:
simple <- function(mod, FUN){
FUNS <- lapply(FUN,match.fun)
lapply(FUNS,function(fun) fun(mod))
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With