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?

1
  • It gives me an error. Commented Oct 22, 2019 at 22:32

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. It is amazing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.