Your code works for me, with the minor exception of the quotations in the filter
statement not printing well.
If you're looking to do this for every tree, you need to look into tidyr
, purrr
and nesting your data into list-columns. What's going on below is:
- Grouping your data by Tree
- Nesting those groups into a list-column
- Create a model column that maps the
lm
function thentidy
to thedata
list-column. - Unnest the model list column.
- Filter it to circumference.
library(tidyverse) #for purrr, tidyr and dplyr
library(broom)
Orange %>%
group_by(Tree) %>%
nest() %>%
mutate(model = map(data, ~lm(age ~ 1 + circumference, data = .x) %>%
tidy)) %>%
unnest(model) %>%
filter(term == 'circumference')
Which results in:
# A tibble: 5 x 6
Tree term estimate std.error statistic p.value
<ord> <chr> <dbl> <dbl> <dbl> <dbl>
1 1 circumference 11.919245 0.9188029 12.97258 4.851902e-05
2 2 circumference 7.795225 0.5595479 13.93129 3.425041e-05
3 3 circumference 12.038885 0.8353445 14.41188 2.901046e-05
4 4 circumference 7.169842 0.5719516 12.53575 5.733090e-05
5 5 circumference 8.787132 0.6211365 14.14686 3.177093e-05
You can then extract what you need using pull
from dplyr
or any other method you prefer.