I need to run many similar regressions with small differences. As such, I want to create a class that creates different objects.
How can I setMethod
so that a linear regression is run within the object? I'm now using "show"
and cat
to define the function, but it's not working.
The model I want to create as an object is:
model_ols <- plm(npl_lnratio ~ qe_ann factor(year), index = "NAME", model = "within", data = mydata)
setClass("definition",
slots = list(dv = "character",
vars = "character",
method = "character",
data = "character",
model = "character")
)
setMethod("show", "definition",
function(object){
cat(object$dv ~ object$model(object$vars, factor(year), index = "NAME", model = object$method, data = object$data))
})
ols <- new("definition",
dv = "npl_lnratio",
vars = "qe_ann",
method = "within",
data = "mydata",
model = "plm")
show(ols)
CodePudding user response:
Your slot definitions shouldn't all be "character" class - you need to indicate the type of data you will be passing in to each:
setClass("definition",
slots = list(dv = "character",
vars = "character",
method = "character",
data = "data.frame",
model = "function",
plm = "list")
)
Secondly, it sounds like you want the model to run when your new object is created. To do this, you will need to define an initialize
method for your class:
setMethod("initialize", "definition",
function(.Object, dv, vars, method, data, model) {
fo <- as.formula(paste0(dv, "~", vars, " factor(year)"))
model_ols <- model(fo, index = "NAME",
model = method,
data = data)
.Object@plm <- list(model_ols)
.Object
}
)
If you only want your show
method to show the regression model, then it should do just that:
setMethod("show", "definition",
function(object) {
print(object@plm[[1]])
})
Before we create an object from your new class, we need to define some random data with the same names as your own data frame. You can skip this step since you already have the data.
set.seed(1)
mydata <- data.frame(year = rep(2010:2020, 3),
qe_ann = sample(100, 33, TRUE),
NAME = rep(c("A", "B", "C"), each = 11))
mydata$npl_lnratio <- mydata$year - 2000 mydata$qe_ann / 100 rnorm(33)
Now we can create an instance of our new class:
ols <- new("definition",
dv = "npl_lnratio",
vars = "qe_ann",
method = "within",
data = mydata,
model = plm)
Remember that show
will be invoked if we simply type the name of our object into the console:
ols
#>
#> Model Formula: npl_lnratio ~ qe_ann factor(year)
#> <environment: 0x00000176689c3ec0>
#>
#> Coefficients:
#> qe_ann factor(year)2011 factor(year)2012 factor(year)2013 factor(year)2014
#> 0.011662 0.222901 0.115303 2.614314 3.563795
#> factor(year)2015 factor(year)2016 factor(year)2017 factor(year)2018 factor(year)2019
#> 4.308154 5.627329 6.624514 7.314393 8.909426
#> factor(year)2020
#> 9.254426