Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a function with a FUN input in r

Tags:

function

r

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.

like image 814
Evan Friedland Avatar asked May 24 '17 18:05

Evan Friedland


People also ask

How do you make an input function in R?

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.

What is the fun function in R?

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 .

Which function can be used in user input in R?

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.


1 Answers

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))
}
like image 136
joran Avatar answered Oct 02 '22 18:10

joran