user3024655
user3024655

Reputation:

R : Define a function from character string

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.

Upvotes: 19

Views: 10350

Answers (1)

Barranka
Barranka

Reputation: 21047

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

Upvotes: 28

Related Questions