R bnlearn eval 内部函数

R bnlearn eval inside function

我正在使用 R 中的 bnlearn 包来训练贝叶斯网络。我在使用以下代码时遇到问题(稍微修改了 bnlearn 示例代码):

library(bnlearn)
data(learning.test)
fitted = bn.fit(hc(learning.test), learning.test)

myfuncBN=function(){

  var = names(learning.test)
  obs = 2
  str = paste("(", names(learning.test)[-3], "=='",
          sapply(learning.test[obs,-3], as.character), "')",
          sep = "", collapse = " & ")
  str2 = paste("(", names(learning.test)[3], "=='",
           as.character(learning.test[obs, 3]), "')", sep = "")
  cpquery(fitted, eval(parse(text = str2)), eval(parse(text = str)))
}

myfuncBN()

此代码抛出错误:

总结期间出错:无法将类型 'closure' 强制转换为类型 'character'

的向量

但是如果 str 和 str2 是在函数 myfuncBN() 之外定义的,它就可以工作。 有人知道这是什么原因吗?

这里是问题的解决方案:

library(bnlearn)
data(learning.test)
fitted = bn.fit(hc(learning.test), learning.test)

myfuncBN=function() {
  vars = names(learning.test)
  obs = 2
  str1 = paste("(", vars[-3], "=='",
          sapply(learning.test[obs,-3], as.character), "')",
          sep = "", collapse = " & ")
  str2 = paste("(", vars[3], "=='",
           as.character(learning.test[obs, 3]), "')", sep = "")

  eval(parse(text=paste("cpquery(fitted,",str2,",",str1,")")))
}

set.seed(1)
myfuncBN()

# [1] 0.05940594

这个值等于给出的结果:

set.seed(1)
cpquery(fitted, event=(C=="c"), 
             evidence=((A=="b") & (B=="a") & (D=="a") & (E=="b") & (F=="b")))

# [1] 0.05940594