2

Hello I am using the package partykit and its function cforest to fit a model. I can also use predict to predict based on a multi-row dataframe. However, I cannot predict on a dataframe with one row.

require('partykit')
y <- matrix(rnorm(500*1),nrow=500,ncol=1)
x <- matrix(rnorm(500*6),nrow=500,ncol=6)
df <- data.frame(y=y,x=x)
obj = cforest(y ~ ., data= df)

#works
predict(obj,newdata=df)

# doesn't work
predict(obj,newdata=df[5,])

#this works
predict(obj,newdata=df[c(5,6),])

The error message is:

predict(obj,newdata=df[5,]) Error in vector(mode = "list", length = ncol(w)) : invalid 'length' argument

lmo
  • 37,904
  • 9
  • 56
  • 69

1 Answers1

3

There does appear to be a bug in the code when you try to predict just one row. The function that's being called is partykit:::predict.cforest. And there's a line in there that says

return(pw[, match(fnewdata, ids)])

but it should be

return(pw[, match(fnewdata, ids), drop=FALSE])

So you can either always call it with one more than one row, or you can hack the function (this is very, very hacky and depends on line numbers in the function so it may break in the future -- tested with partykit_1.0-5) like so

mypredict <- partykit:::predict.cforest
body(mypredict)[[c(13,3,3,3,8)]] <- quote(return(pw[, match(fnewdata, ids), drop=FALSE]))
mypredict(obj, newdata=df[6,])
#          5 
# 0.04755628

Now we have a new function that should handle the case of one row correctly

MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • 2
    An even better solution is to contact one of the `partykit` authors (not everyone is watching SO all of the time) and ask them to add your fix. This author has done so now and the fixed version will be available from R-Forge soon: https://R-Forge.R-project.org/R/?group_id=261 Thanks for spotting this and suggesting the fix! – Achim Zeileis Apr 30 '16 at 07:57