3

I want to use information from a field and include it in a R function, e.g.:

data #name of the data.frame with only one raw

"(if(nclusters>0){OptmizationInputs[3,3]*beta[1]}else{0})" # this is the raw

If I want to use this information inside a function how could I do it?

Another example:
A=c('x^2')
B=function (x) A
B(2)
"x^2"  # this is the return. I would like to have the return something like 2^2=4.
Kara
  • 6,115
  • 16
  • 50
  • 57
Eliano
  • 63
  • 4

3 Answers3

3

Use body<- and parse

A <- 'x^2'

B <- function(x) {}

body(B) <- parse(text = A)

B(3)
## [1] 9

There are more ideas here

Community
  • 1
  • 1
mnel
  • 113,303
  • 27
  • 265
  • 254
3

Another option using plyr:

A <- 'x^2'
library(plyr)
body(B) <- as.quoted(A)[[1]]
> B(5)
[1] 25
agstudy
  • 119,832
  • 17
  • 199
  • 261
2
A  <- "x^2"; x <- 2
BB <- function(z){ print( as.expression(do.call("substitute", 
                                            list( parse(text=A)[[1]], list(x=eval(x) ) )))[[1]] ); 
               cat( "is equal to ", eval(parse(text=A)))
              }
 BB(2)
#2^2
#is equal to  4

Managing expressions in R is very weird. substitute refuses to evaluate its first argument so you need to use do.call to allow the evaluation to occur before the substitution. Furthermore the printed representation of the expressions hides their underlying representation. Try removing the fairly cryptic (to my way of thinking) [[1]] after the as.expression(.) result.

IRTFM
  • 258,963
  • 21
  • 364
  • 487