Laura, you can directly access the model in this way <modelo>$finalModel
and execute predict
as you normally do. Let's see an example:
df <- read.table(text = 'Cobranza Facturacion
100 200
200 400
300 600
100 220
100 210', header=TRUE)
cobranza.lm <- lm(Cobranza ~ Facturacion, data=df)
This is to create a basic linear model to predict a collection based on your billing, now if I want to predict this value from a billing data of 150$
, we can do this:
newdata <-data.frame(Facturacion = c(150))
predict(cobranza.lm, newdata, interval="predict")
This will return us, the value and the requested interval:
fit lwr upr
1 69.61691 52.76363 86.47019
If we use the caret
package, you can do the same thing you ask, but from slightly different way:
library("caret")
cobranza.caret.lm <- train(Cobranza ~ Facturacion, data=df, method='lm')
predict(cobranza.caret.lm$finalModel, newdata, interval = "predict")
As you can see, we built the same previous model, which we can access from cobranza.caret.lm$finalModel
, and use it directly in predict
as we did before. We should get the same intervals:
fit lwr upr
1 69.61691 52.76363 86.47019
Important Note : The parameter interval
is typical of the Class of the defined model, particularly implemented by the models lm
and nls
, for any other model that does not implement it, the parameter will be ignored.