R中的Eval和环境:为什么Eval()找不到在评估表达式的环境中定义的变量

时间:2013-11-25 17:56:25

标签: r

我对评估表达式的环境有疑问。具体来说,我有一个函数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, ]))    
}   

1 个答案:

答案 0 :(得分:0)

我遇到了这样的问题。我通过对函数中未找到的变量进行超级分配解决了该问题。

var <<- 5
相关问题