18

I'd like to define a function f from parameters and an expression that are character strings read from a .csv file. This function f has the following expression :

f = function( parameters ) { expression }

where parameters are a list of n parameters and the expression is a function of these parameters. For example: the parameters are x1,x2,x3, and expression is (x1+x2)*x3. The function f is then f = function(x1,x2,x3){ (x1+x2)*x3 }. How I proceed in R to define such functions ?

EDIT add more context:

Given 2 charcaters strings , for body and arguments

body="(x1+x2)*x3"
args = "x1,x2,x3"

How we can get ?:

function (x1, x2, x3) 
(x1 + x2) * x3

Note that this question is similar but don't answer exactly this one, since the solution proposed don't create the function formals (arguments) from a character string.

Community
  • 1
  • 1
  • 2
    What have you tried already? What specific problem are you getting stuck on? If you need to learn the basics of coding, this isn't the place. If you have a specific issue in translating this problem into code, show us what you have tried. – Ideasthete Oct 02 '14 at 15:21
  • 1
    Have a look at the examples in `?as.function`. It's not quite the same, but might be interesting. – GSee Oct 02 '14 at 16:43

1 Answers1

26

eval() and parse(), used together, may help you do what you want:

body <- "(x1 + x2) * x3"
args <- "x1, x2, x3"

eval(parse(text = paste('f <- function(', args, ') { return(' , body , ')}', sep='')))
# Text it:
f(3,2,5)
## 10

The explanation: parse() will return the parsed, but unevaluated, expression. I use the text argument in the function to pass a string to the parser. eval() will evaluate the parsed expression (in this case, it will execute the code block you've just parsed).

Hope this helps

Barranka
  • 20,547
  • 13
  • 65
  • 83