Home > Enterprise >  R: how to create an object of class "rq" manually?
R: how to create an object of class "rq" manually?

Time:09-28

How can I create manually an object of class "rq" such that I can use it afterwards to run the predict function?

Thanks to your very useful replies, mymdl is now of class "rq" in this example. Adding class(mymdl$coefficients) ="numeric" to the code solved my main issue: predict(mymdl) works.

Interestingly enough, class(mdl$terms) and class(mymdl$terms) differ. If I set class(mymdl$terms) = class(mdl$terms), then predict(mymdl) produces NAs. I am wondering why this is happening..

library(quantreg)

data(engel)                                 #load dataset
engel2 <- engel[1:100,]                     #keep subset for prediction
reg_formula <- foodexp ~ income             #define regression formula
mdl <- rq(reg_formula,.5, data = engel)     #run regression

#------------------------------------------
#remove non-essential information from mdl
#mdl$coefficients <- NULL
mdl$x <- NULL
mdl$y <- NULL
mdl$residuals <- NULL
mdl$dual <- NULL
mdl$fitted.values <- NULL
mdl$formula <- NULL
#mdl$terms <- NULL
mdl$xlevels <- NULL
mdl$call <- NULL
mdl$tau <- NULL
mdl$rho <- NULL
mdl$method <- NULL
mdl$model <- NULL

#Only mdl$coefficients and mdl$terms are
#essential for predicting
#------------------------------------------

engel2$foodexp_pr <- predict(mdl, newdata = engel2) #predict


#create own regression model
mymdl <- NULL
mymdl[["coefficients"]][["(Intercept)"]] <- 81.48225
mymdl[["coefficients"]][["income"]] <- 0.5601806
mymdl$terms <- reg_formula

class(mymdl) <- "rq"
class(mymdl$coefficients) ="numeric"

engel2$foodexp_pr2 <- predict(mymdl, newdata = engel2) #works

#Minor question: why does predict produce NAs in this case?
class(mymdl$terms) = class(mdl$terms)
engel2$foodexp_pr3 <- predict(mymdl, newdata = engel2) #produces NAs

I am new to working with classes. Any help and advice is welcome.

EDIT 1: I have expanded my example and incorporated your very helpful feedback. mymdl is now an "rq"-class. I have also identified the most essential information used by the predict function (i.e., mdl$coefficients and mdl$terms).

EDIT 2: Added my solution to the example. However, there is still a minor open question.

CodePudding user response:

The S3 class system is very loose. You can make an object be class "rq" just by adding that to its class:

class(mymdl) <- "rq"

or more generally

class(mymdl) <- c("rq", class(mymdl))

This doesn't mean that predict.rq is going to work; for that you need to check what it needs, and that's not always easy.

  • Related