3

我想使用字段中的信息并将其包含在 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.
4

3 回答 3

3

使用body<-和解析

A <- 'x^2'

B <- function(x) {}

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

B(3)
## [1] 9

这里有更多的想法

于 2013-03-07T00:14:31.803 回答
3

另一个选项使用plyr

A <- 'x^2'
library(plyr)
body(B) <- as.quoted(A)[[1]]
> B(5)
[1] 25
于 2013-03-07T00:18:56.413 回答
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

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

于 2013-03-07T03:06:58.693 回答