add_predictions: Add predictions to a data frame

Description Usage Arguments Value Examples

View source: R/predictions.R

Description

Add predictions to a data frame

Usage

1
2
3
4
5
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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
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)

m2 <- lm(y ~ poly(x, 2), data = df)
grid %>% spread_predictions(m1, m2)
grid %>% gather_predictions(m1, m2)

Example output

           x     pred
1  0.0000000 2.857846
2  0.1111111 3.453938
3  0.2222222 4.050030
4  0.3333333 4.646122
5  0.4444444 5.242214
6  0.5555556 5.838306
7  0.6666667 6.434398
8  0.7777778 7.030490
9  0.8888889 7.626582
10 1.0000000 8.222674
           x       m1       m2
1  0.0000000 2.857846 2.852988
2  0.1111111 3.453938 3.452126
3  0.2222222 4.050030 4.050466
4  0.3333333 4.646122 4.648008
5  0.4444444 5.242214 5.244752
6  0.5555556 5.838306 5.840697
7  0.6666667 6.434398 6.435845
8  0.7777778 7.030490 7.030194
9  0.8888889 7.626582 7.623745
10 1.0000000 8.222674 8.216498
   model         x     pred
1     m1 0.0000000 2.857846
2     m1 0.1111111 3.453938
3     m1 0.2222222 4.050030
4     m1 0.3333333 4.646122
5     m1 0.4444444 5.242214
6     m1 0.5555556 5.838306
7     m1 0.6666667 6.434398
8     m1 0.7777778 7.030490
9     m1 0.8888889 7.626582
10    m1 1.0000000 8.222674
11    m2 0.0000000 2.852988
12    m2 0.1111111 3.452126
13    m2 0.2222222 4.050466
14    m2 0.3333333 4.648008
15    m2 0.4444444 5.244752
16    m2 0.5555556 5.840697
17    m2 0.6666667 6.435845
18    m2 0.7777778 7.030194
19    m2 0.8888889 7.623745
20    m2 1.0000000 8.216498

modelr documentation built on July 1, 2020, 7:03 p.m.