Complicated constructors can be defined using the initialize
method, which will automatically be called when you call new
. I've modified your example to contain the initialize method, and a new field to store the regression result, because initialize
will always return the referenceClass
:
linRegClass = setRefClass('linRegClass',
fields = list(formulaReg = 'formula',
dataReg = 'data.frame',
result = 'lm'),
methods = list(doReg = function() {
lm(.self$formulaReg, data = .self$dataReg)
},
initialize = function(formulaReg, dataReg, ...) {
formulaReg <<- formulaReg
dataReg <<- dataReg
result <<- .self$doReg()
}))
So now we simply have:
linRegInstance <- linRegClass$new(dataReg = cars,
formulaReg = as.formula(speed ~ dist))
linRegInstance$result