R bnlearn eval inside function

落花浮王杯 提交于 2019-12-20 02:39:17

问题


I am using the bnlearn package in R to train a Bayesian network. I have troubles with the following code (slightly modified bnlearn example code):

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()

This code throws the error:

Error during wrapup: cannot coerce type 'closure' to vector of type 'character'

It works however if str and str2 are defined outside the function myfuncBN(). Does anyone know the reason for this?


回答1:


Here is a solution to the problem:

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

This value is equal to the result given by:

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

# [1] 0.05940594


来源:https://stackoverflow.com/questions/44676501/r-bnlearn-eval-inside-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!