I am trying to extract the parameters of a model I have designed for my work, but am having trouble doing so. I will use the iris data provided with R as an example data set.
I pull in the data:
library(dplyr)
df <- iris
I design a model that takes Sepal Width and Length, and determines what the best model fit given Sepal Length is to determine Sepal Width (this is probably a bad example of a data set, and I didn't pay much attention to the starting parameters, but I am almost certain this shouldn't affect how hard it is to answer this question). One model is produced for each Species:
sepalmodel <- df %>%
group_by(Species) %>%
do(model = nls(Sepal.Width ~ a*exp(Sepal.Length*b), start = list(a = 0.5, b = 0.9), data = .)) %>%
ungroup()
This produces a dataframe with one column being Species, and the other being model. In the model column, each model is represented in each row by a large list, which I have trouble extracting its basic data from. I would like to work with the parameters directly, as a more clean and reproducible way of representing and generating data with these models. How can I extract the a and b parameters from these models? Is there a function that does so, or do I need to dig into the code of each model? Also, is there any data built into that list that associates it with the specific species, or is it only directly associated with the species by nature of being found in the same row?
One option is to use broom::tidy
with tidyr::unnest
.
library(tidyverse)
iris %>%
group_by(Species) %>%
do(model = nls(Sepal.Width ~ a*exp(Sepal.Length*b), start = list(a = 0.5, b = 0.9), data = .)) %>%
ungroup() %>%
mutate(tidy_nls = lapply(model, broom::tidy)) %>%
unnest(tidy_nls)
#------
# A tibble: 6 x 7
Species model term estimate std.error statistic p.value
<fct> <list> <chr> <dbl> <dbl> <dbl> <dbl>
1 setosa <nls> a 1.07 0.162 6.58 3.23e- 8
2 setosa <nls> b 0.232 0.0299 7.76 5.12e-10
3 versicolor <nls> a 1.41 0.228 6.18 1.31e- 7
4 versicolor <nls> b 0.113 0.0269 4.21 1.11e- 4
5 virginica <nls> a 1.80 0.261 6.87 1.17e- 8
6 virginica <nls> b 0.0764 0.0218 3.51 9.97e- 4