R bnlearn eval inside function

前端 未结 1 2047
长发绾君心
长发绾君心 2020-12-19 14:58

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


        
1条回答
  •  自闭症患者
    2020-12-19 15:42

    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
    

    0 讨论(0)
提交回复
热议问题