Information Technology Reference
In-Depth Information
See Also
The car package is not part of the standard distribution of R; download and install it
using the install.packages function.
1.24 Predicting New Values
Problem
You want to predict new values from your regression model.
Solution
Save the predictor data in a data frame. Use the predict function, setting the newdata
parameter to the data frame:
> m <- lm(y ~ u + v + w)
> preds <- data.frame(u=3.1, v=4.0, w=5.5)
> predict(m, newdata=preds)
Discussion
Once you have a linear model, making predictions is quite easy because the predict
function does all the heavy lifting. The only annoyance is arranging for a data frame to
contain your data.
The predict function returns a vector of predicted values with one prediction for every
row in the data. The example in the Solution contains one row, so predict returns one
value:
> preds <- data.frame(u=3.1, v=4.0, w=5.5)
> predict(m, newdata=preds)
1
12.31374
If your predictor data contains several rows, you get one prediction per row:
> preds <- data.frame(
+ u=c(3.0, 3.1, 3.2, 3.3),
+ v=c(3.9, 4.0, 4.1, 4.2),
+ w=c(5.3, 5.5, 5.7, 5.9) )
> predict(m, newdata=preds)
1 2 3 4
11.97277 12.31374 12.65472 12.99569
In case it's not obvious, the new data needn't contain values for response variables,
only predictor variables. After all, you are trying to calculate the response, so it would
be unreasonable of R to expect you to supply it.
 
Search WWH ::




Custom Search