1

I want to write a function. However, the assumption is that I don't know the input arguments of the function. I just have a character vector to define input arguments of the function. Consider the following code:

f <- expression(exp(-d^2/s^2) )
fx <- function(d, s){ eval( f[[1]] ) }

In the above code, I know the parameters of expression and easily define a calculative function for it. But I get the expression from the user and I don't know what are the parameters. So, I want something like this:

f <- expression(exp(-d^2/s^2) )
v = all.vars(f)
#"d" "s"
fx <- function(?){ eval( f[[1]] ) }

I want to convert v to d and s on input function instead of ?. Is there any way?

mohammad
  • 175
  • 2
  • 13

1 Answers1

3

There are a few ways to construct functions programmatically, one being:

body <- quote(exp(-d^2/s^2))
arg_names <- all.vars(body)
args <- setNames(rep(NA,length(arg_names)),all.vars(body))
fx <- as.function(c(args,body))

>   fx(1,1)
[1] 0.3678794
joran
  • 169,992
  • 32
  • 429
  • 468