我在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()
此代码抛出错误:
包装错误:无法强制类型'关闭'到#'字符'
的矢量但是如果在函数myfuncBN()之外定义了str和str2,则它可以工作。 有谁知道这个的原因?
答案 0 :(得分:1)
以下是问题的解决方案:
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