## Generate data to fit models
simple_linear_data = specify(a = ~ 2 + rnorm(n),
b = ~ 5 + 3*a + rnorm(n, 0, sd = 0.5)) %>%
define(n = 100:101) %>%
generate(2)
## Fit with a single linear term
linear_fit = simple_linear_data %>%
fit(linear = ~lm(b ~ a, data = .))
linear_fit # first fit element also prints
## Each element of $linear is a model object
linear_fit$linear
## We can fit multiple models to the same data
multi_fit = simple_linear_data %>%
fit(linear = ~lm(b ~ a, data = .),
quadratic = ~lm(b ~ a + I(a^2), data = .))
## Two columns, one for each model
multi_fit
## Again, each element is a model object
multi_fit$quadratic
## Can view terms more nicely with tidy_fits
multi_fit %>%
tidy_fits
## Can view model summaries with glance_fits
multi_fit %>%
glance_fits
## Fit functions do not actually need to be any particular kind of model, they
## can be any arbitrary function. However, not all functions will lead to useful
## output with tidy_fits and glance_fits.
add_five_data = simple_linear_data %>%
fit(add_five = ~ . + 5) ## adds 5 to every value in dataset
add_five_data
Run the code above in your browser using DataLab