Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
860 views
in Technique[技术] by (71.8m points)

dplyr - How do I extract parameters from listed models in R?

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?

question from:https://stackoverflow.com/questions/65927675/how-do-i-extract-parameters-from-listed-models-in-r

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...