2013-03-06 81 views
2

我想从一个字段中使用的信息,并将其纳入A R的功能,例如:[R转换文本字段的功能

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

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

如果我想使用的功能,我怎么能做到这一点这里面的信息?

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. 

回答

2

使用body<-和解析

A <- 'x^2' 

B <- function(x) {} 

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

B(3) 
## [1] 9 

here

2

另一种选择使用plyr有更多的想法:

A <- 'x^2' 
library(plyr) 
body(B) <- as.quoted(A)[[1]] 
> B(5) 
[1] 25 
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 

Managi R中的ng表达式非常奇怪。 substitute拒绝评估其第一个参数,因此您需要使用do.call以允许在替换之前进行评估。此外,表达式的打印表示隐藏了它们的基本表示。尝试删除相当神秘(以我的思路)[[1]]as.expression(.)结果。