Ryan Morrison
2013-Oct-09 17:20 UTC
[R] Using "cpquery" function from bnlearn package inside loop
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! [[alternative HTML version deleted]]
Ryan Morrison
2013-Oct-09 20:26 UTC
[R] Using "cpquery" function from bnlearn package inside loop
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!