Skip to content

Add predictions to a data frame

Usage

add_predictions(data, model, var = "pred", type = NULL)

spread_predictions(data, ..., type = NULL)

gather_predictions(data, ..., .pred = "pred", .model = "model", type = NULL)

Arguments

data

A data frame used to generate the predictions.

model

add_predictions takes a single model;

var

The name of the output column, default value is pred

type

Prediction type, passed on to stats::predict(). Consult predict() documentation for given model to determine valid values.

...

gather_predictions and spread_predictions take multiple models. The name will be taken from either the argument name of the name of the model.

.pred, .model

The variable names used by gather_predictions.

Value

A data frame. add_prediction adds a single new column, with default name pred, to the input data. spread_predictions adds one column for each model. gather_predictions

adds two columns .model and .pred, and repeats the input rows for each model.

Examples

df <- tibble::tibble(
  x = sort(runif(100)),
  y = 5 * x + 0.5 * x ^ 2 + 3 + rnorm(length(x))
)
plot(df)


m1 <- lm(y ~ x, data = df)
grid <- data.frame(x = seq(0, 1, length = 10))
grid %>% add_predictions(m1)
#>            x     pred
#> 1  0.0000000 2.814380
#> 2  0.1111111 3.441413
#> 3  0.2222222 4.068446
#> 4  0.3333333 4.695478
#> 5  0.4444444 5.322511
#> 6  0.5555556 5.949544
#> 7  0.6666667 6.576577
#> 8  0.7777778 7.203610
#> 9  0.8888889 7.830642
#> 10 1.0000000 8.457675

m2 <- lm(y ~ poly(x, 2), data = df)
grid %>% spread_predictions(m1, m2)
#>            x       m1       m2
#> 1  0.0000000 2.814380 2.358486
#> 2  0.1111111 3.441413 3.263516
#> 3  0.2222222 4.068446 4.098546
#> 4  0.3333333 4.695478 4.863576
#> 5  0.4444444 5.322511 5.558606
#> 6  0.5555556 5.949544 6.183635
#> 7  0.6666667 6.576577 6.738664
#> 8  0.7777778 7.203610 7.223693
#> 9  0.8888889 7.830642 7.638722
#> 10 1.0000000 8.457675 7.983750
grid %>% gather_predictions(m1, m2)
#>    model         x     pred
#> 1     m1 0.0000000 2.814380
#> 2     m1 0.1111111 3.441413
#> 3     m1 0.2222222 4.068446
#> 4     m1 0.3333333 4.695478
#> 5     m1 0.4444444 5.322511
#> 6     m1 0.5555556 5.949544
#> 7     m1 0.6666667 6.576577
#> 8     m1 0.7777778 7.203610
#> 9     m1 0.8888889 7.830642
#> 10    m1 1.0000000 8.457675
#> 11    m2 0.0000000 2.358486
#> 12    m2 0.1111111 3.263516
#> 13    m2 0.2222222 4.098546
#> 14    m2 0.3333333 4.863576
#> 15    m2 0.4444444 5.558606
#> 16    m2 0.5555556 6.183635
#> 17    m2 0.6666667 6.738664
#> 18    m2 0.7777778 7.223693
#> 19    m2 0.8888889 7.638722
#> 20    m2 1.0000000 7.983750