【问题标题】:Eval and environments in R: Why can't Eval() find a variable defined in the environment where it evaluates the expressionR 中的 Eval 和环境:为什么 Eval() 找不到在计算表达式的环境中定义的变量
【发布时间】:2013-11-25 17:56:24
【问题描述】:

我有一个关于评估表达式的环境的问题。具体来说,我有一个函数 bnlearn::cpdist 将逻辑表达式作为参数。我希望使用一个变量来指定该参数,所以我希望使用 eval(parse(text = string))。但如果这种情况发生在更大函数的环境中,则 eval 函数无法找到变量“string”,尽管它已在该环境中定义。我很困惑。这是重现问题的代码。

# The function is from the bnlearn package, which handles Bayesian networks
library(bnlearn)
#Example data
data(learning.test)
#Fitting a model
fitted = bn.fit(hc(learning.test), learning.test)
#The function in question generates samples from the PDF of one node given the values of others.  
posterior = cpdist(fitted, "D", (A == "a" & C == "b")) #Notice the awkward logical statement arg
prop.table(table(posterior))

#I want to use character variables instead of the logical statement.
#If I use parse and eval to specify the logical statement I have no issues.
evidence.nodes <- c("A", "C")
evidence.values <- c("a", "b")
ev <- paste("(", evidence.nodes, "=='",
                  sapply(evidence.values, as.character), "')",
                  sep = "", collapse = " & ")
posterior <- cpdist(fitted, "D", eval(parse(text = ev)))


#But what I want to do is apply do this from within a function
getPosterior <- function(fitted, target, ev.nodes, ev.values){
    ev <- paste("(", ev.nodes, "=='",
                  sapply(ev.values, as.character), "')",
                  sep = "", collapse = " & ")

     posterior <- cpdist(fitted, "D", eval(parse(text = ev)))
     prop.table(table(posterior))
}

#Here is where the problem lies.  The following works if "ev" is already defined as it was above.  However, if you remove ev from the global environment, then it fails.  I do not understand why it cannot find the ev object defined within the function's environment.

new.data <- data.frame(A = c("a", "b", "a", "b"), C = c("a", "a", "b", "b"))    
rm(ev)
for(i in 1:nrow(new.data)){
    print(getPosterior(fitted, "D", names(new.data), new.data[i, ]))    
}   

【问题讨论】:

  • 这里有很多问题,但首先,错误来自parse() 而不是eval()。如果你解决了这个问题,那么你会得到另一个错误,这次来自eval()。您希望在哪里或在什么对象中评估表达式 ev(来自 getPosterior())? IE。它应该在哪里找到A 等。
  • 你问了一个关于 eval() 变量范围的简单问题,但你提供了过于复杂和不相关的代码......(-1,抱歉)
  • 我投票决定关闭你的earlier version 这个问题,因为这实际上是一个改进(恕我直言)。
  • 感谢 cmets。我给出了代码是因为人们似乎希望能够重现该错误。我没有得到的是代码有效 eval() 在全局环境中定义时可以找到“ev”对象,但在函数中定义时找不到。

标签: r


【解决方案1】:

我遇到了这样的问题。我通过对我的函数中找不到的变量进行超级赋值来解决它。

var <<- 5

【讨论】:

    猜你喜欢
    • 2018-10-02
    • 1970-01-01
    • 2016-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-09
    相关资源
    最近更新 更多