R: Define a function from a character string

I would like to define a function ffrom parameters and an expression that are characterstrings read from a file .csv. This function fhas the following expression:

f = function( parameters ) { expression }

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

EDIT add more context:

Given two lines of characters, for body and arguments

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

How can we get ?:

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

Please note that this question is similar, but does not answer exactly this, since the proposed solution does not create function forms (arguments) from a character string.

+6
1

eval() parse(), , , :

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

: parse() , . text . eval() ( ).

+9

All Articles