a b
a b

Reputation: 171

Use variable name as argument in partialPlot from randomForest package

I'm using a library that has a function, f. This function accepts a few arguments: an object, a dataframe, and the name of a column in the dataframe. If I call it manually, it works without any trouble. I call it like this:

f(my_object, my_dataframe, 'A')

However, if I put 'A' in a variable, it doesn't work! To clarify, I just do this:

g = 'A'    
f(my_object, my_dataframe, g)

And I get an error (undefined columns selected). I've tried googling to figure this out, but no luck. If anyone could help I would really appreciate it.


EDIT: I'm using the partialPlot command in the randomForest library. Here's exactly what I'm typing:

partialPlot(r,x,'pH')

This works! Next, I assign 'pH' to a variable and try the exact same function:

g = 'pH'    
partialPlot(r,x,g)

This doesn't work and I get the following error:

Error in '[.data.frame'(pred.data, , xname) : undefined columns selected

I can also verify that g is what I think it is:

print(g)
#[1] "pH"

class(g)
#[1] "character"

Upvotes: 3

Views: 1281

Answers (2)

Arthur
Arthur

Reputation: 2410

I encountered this problem myself. This is a messy solution, but it worked for me. Using eval() is considered bad programming, but the bug in partialPlot is so mind-boggling, I think desperate times call for desperate measures!

To.Eval <- paste("partialPlot(r, x, '", 
                  g, 
                  "')", 
                  sep = "")
L <- eval(parse(text = To.Eval))

Upvotes: 1

unique2
unique2

Reputation: 2302

Try

g = quote(pH)
partialPlot(r,x,g)

The culprit is the following piece in randomForest:::partialPlot.randomForest

x.var <- substitute(x.var)
xname <- if (is.character(x.var)) 
    x.var
else {
    if (is.name(x.var)) 
        deparse(x.var)
    else {
        eval(x.var)
    }
}

For more background see stackoverflow.com/q/9860090/1201032


Earlier try (only worked interactively):

partialPlot(r,x,c(g)) should work.Writing c(g) instead of g makes is.name(x.var) return FALSE so eval instead of deparse gets executed.

Upvotes: 3

Related Questions