[R] Using "cpquery" function from bnlearn package inside loop

Ryan Morrison ryan.r.morrison at me.com
Wed Oct 9 22:26:14 CEST 2013


Hi everyone, 

I'm attempting to use the bnlearn package to calculate conditional probabilities, and I'm running into a problem when the "cpquery" function is used within a loop. I've created an example, shown below, using data included with the package. When using the cpquery function in a loop, a variable created in the loop ("evi" in the example) is not recognized by the function. I receive the error: 

Error in parse(text = evi) : object 'evi' not found 

The creation steps of "evi" are based on examples provided by the author. 

Any help you could provide would be great. I'm eager to find a way that I can apply the cpquery function for a large number of observations. 

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

bn.function <- function(network, evidence_data) { 
  a <- NULL 
  b <- nrow(evidence_data) 
  for (i in 1:b) { 
    evi <- paste("(", names(evidence_data), "=='", 
               sapply(evidence_data[i,], as.character), "')", 
               sep = "", collapse = " & ") 
    a[i] <- cpquery(network, (C=='c'), eval(parse(text=evi))) 
  } 
  return(a) 
} 

test <- bn.function(fitted, learning.test) 

Thanks for your help!


More information about the R-help mailing list