bgreenwell / pdp

A general framework for constructing partial dependence (i.e., marginal effect) plots from various types machine learning models in R.
http://bgreenwell.github.io/pdp
91 stars 12 forks source link

Class inheritance should be changed to c("partial", "data.frame") instead of c("data.frame", "partial") #104

Closed RoelVerbelen closed 4 years ago

RoelVerbelen commented 4 years ago

I'm experiencing unexpected errors as a result of the order of the classes of a partial object. I believe they can be addressed by changing the order of the classes of a partial object such that the inheritance of methods works as expected.

For reference: http://adv-r.had.co.nz/S3.html https://adv-r.hadley.nz/s3.html#s3-inheritance

# Construct partial object
library(pdp)
library(randomForest)
data(boston)  
set.seed(101)  
boston.rf <- randomForest(cmedv ~ ., data = boston)
pd <- partial(boston.rf, pred.var = c("lstat", "rm"), grid.resolution = 40)

# Inspect class
class(pd)
#> [1] "data.frame" "partial"

# Data manipulation fails
library(dplyr)
pd %>% 
  select(yhat)
#> Error: `x` must be a vector, not a `data.frame/partial` object

# Change class
class(pd) <- c("partial", "data.frame")

# Data manipulation works
pd %>% 
  select(yhat) %>% 
  head()
#>       yhat
#> 1 29.57550
#> 2 29.57337
#> 3 29.28864
#> 4 27.49390
#> 5 25.15407
#> 6 24.74364

# And partial specific functions still work as expected
plotPartial(pd, levelplot = FALSE, zlab = "cmedv", drape = TRUE,
            colorkey = FALSE, screen = list(z = -20, x = -60))

Created on 2020-02-19 by the reprex package (v0.3.0)

bgreenwell commented 4 years ago

Thanks @RoelVerbelen for the helpful reprex. I’m on travel this week, but will push a fix soon. I also anticipate updating the version on CRAN by the end of March.

bgreenwell commented 4 years ago

Thanks @RoelVerbelen for the reprex! I'm on travel right now, but will push an update early next week. I should have a long overdue update to CRAN by the end of March as well.

bgreenwell commented 4 years ago

Actually, @RoelVerbelen, it looks like this was already fixed back in December and has been part of the development version since (albeit, undocumented in NEWS.md)! Working on a CRAN release this week and next.