[R] Force evaluation of variable when calling partialPlot

gdillon gdillon at fs.fed.us
Mon Nov 15 21:29:08 CET 2010


RE: the folloing original question:
> I'm using the randomForest package and would like to generate partial
> dependence plots, one after another, for a variety of variables:
> 
> m <- randomForest( s, ... )
> varnames <- c( "var1", "var2", "var3", "var4" )   # var1..4 are all in
> data frame s
> for( v in varnames ) {
>    partialPlot( x=m, pred.data=s, x.var=v )
> }
> 
> ...but this doesn't work, with partialPlot complaining that it can't
> find the variable "v".

I'm having a very similar problem using the partialPlot function. A
simplified version of my code looks like this:

data.in <- paste(basedir,"/sw_climate_dataframe_",root.name,".csv",sep="")
data <- read.csv(data.in)
vars <- c("sm1","precip.spring","tmax.fall","precip.fall")  #selected
variables in data frame
xdata <- as.data.frame(data[,vars])
ydata <- data[,5]
ntree <- 2000

rf.pdplots <- function() {
  sel.rf <- randomForest(xdata,ydata,ntree=ntree,keep.forest=TRUE)
  par(family="sans",mfrow=c(2,2),mar=c(4,3,1,2),oma=c(0,3,0,0),mgp=c(2,1,0))
  for (i in 1:length(vars)) {
    print((vars)[i])
    partialPlot(sel.rf,xdata,vars[i],which.class=1,xlab=vars[i],main="")
    mtext("(Logit of probability of high severity)/2", side=2, line=1,
outer=T)
  }
}

rf.pdplots()

When I run this code, with partialPlots embedded in a function, I get the
following error:
Error in eval(expr, envir, enclos) : object "i" not found

If I just take the code inside the function and run it (not embedded in the
function), it runs just fine. Is there some reason why partialPlots doesn't
like to be called from inside a function?

Other things I've tried/noticed:
1. If I comment out the line with the partialPlots call (and the next line
with mtext), the function runs as expected and prints the variable names one
at a time.
2. If the variable i is defined as a number (e.g., 4) in the global
environment, then the function will run, the names print out one at a time,
and four plots are created. HOWEVER, the plots are all for the last (4th)
variable, BUT the x labels actually are different on each plot (i.e., the
xlab is actually looping through the four values in vars).

Can anyone help me make sense of this? Thanks.

-Greg
-- 
View this message in context: http://r.789695.n4.nabble.com/Force-evaluation-of-variable-when-calling-partialPlot-tp2954229p3043750.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list