【问题标题】:R convert text field to functionR将文本字段转换为函数
【发布时间】:2013-03-06 23:29:53
【问题描述】:

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

【问题讨论】:

    标签: r


    【解决方案1】:

    使用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
      

      【讨论】:

        【解决方案3】:
        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 以允许在替换之前进行评估。此外,表达式的印刷表示隐藏了它们的基本表示。尝试在 as.expression(.) 结果之后删除相当神秘的(以我的思维方式)[[1]]

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-01-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多