Search code examples
rfunctionparameter-passingbnlearn

Why I'm receiving "Object" not found within this function?


query_averager <- function(arg1,
                           arg2) {
n = tibble()
   i = 1
   while (i <= 100) {
   n[i] <- cpquery(fitted = fitted_bn_01,
        event = (ret == "Acima da Selic") ,
        evidence = (solidez == arg1) & (resultado == arg2))
   i = i+1

   }
return (mean(n))
}

Query_result <- query_averager(arg1 = "1", arg2 = "Lucro acima da mediana")

This gives me "object arg1 not found", but when I use the function cpquery() outside, it works perfectly.

Working code without the query_averager function:

cpquery(fitted = fitted_bn_01,
    event = (ret == "Acima da Selic") ,
    evidence = (solidez == "1") & (resultado == "Lucro acima da median"))

I believe it doesn't matter what the other variables are, the main problem is why:

 solidez == "1"

works and the code snippet below doesn't:

solidez == arg1

Solution

  • It seems you haven't have any variables in the evidence expression because they will not be evaluated in the function body. So it seems you have to manipulate the function call prior to evaluation. I don't have this package installed and working, but it seems like this would work:

    query_averager <- function(arg1, arg2) {
       n = tibble()
       i = 1
       while (i <= 100) {
       n[i] <- eval(substitute(cpquery(fitted = fitted_bn_01,
            event = (ret == "Acima da Selic") ,
            evidence = (solidez == arg1) & (resultado == arg2))))
       i = i+1
    
       }
      mean(n)
    }
    

    The substitute() part injects the values of arg1 and arg2 into the expression. Then we evaluate that expression with eval().