【发布时间】: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