简体   繁体   中英

predicting linear regression by group with dplyr

Building off this question: Add Column of Predicted Values to Data Frame with dplyr

If I run the code in the accepted answer:

library(dplyr)
library(purrr)
library(tidyr)

# generate the inputs like in the question
example_table <- data.frame(x = c(1:5, 1:5),
                            y = c((1:5) + rnorm(5), 2*(5:1)),
                            groups = rep(LETTERS[1:2], each = 5))

models <- example_table %>% 
  group_by(groups) %>% 
  do(model = lm(y ~ x, data = .)) %>%
  ungroup()
example_table <- left_join(tbl_df(example_table ), models, by = "groups")


# generate the extra column
example_table %>%
  group_by(groups) %>%
  do(modelr::add_predictions(., first(.$model))) %>% mutate(model = NULL)

I end up with the predictions stored in a list:

   x         y groups                                             pred
1  1  1.798848      A 1.645775, 2.233358, 2.820940, 3.408523, 3.996105
2  2  2.936818      A 1.645775, 2.233358, 2.820940, 3.408523, 3.996105
3  3  1.513431      A 1.645775, 2.233358, 2.820940, 3.408523, 3.996105
4  4  3.300870      A 1.645775, 2.233358, 2.820940, 3.408523, 3.996105
5  5  4.554734      A 1.645775, 2.233358, 2.820940, 3.408523, 3.996105
6  1 10.000000      B                                   10, 8, 6, 4, 2
7  2  8.000000      B                                   10, 8, 6, 4, 2
8  3  6.000000      B                                   10, 8, 6, 4, 2
9  4  4.000000      B                                   10, 8, 6, 4, 2
10 5  2.000000      B                                   10, 8, 6, 4, 2

Is there any way to have each row (y ~ x) have 1 predicted value? And not a list for the whole group?

Had a conflict with xts package. This solved it:

example_table %>%
  group_by(groups) %>%
  do(modelr::add_predictions(., dplyr::first(.$model))) %>% mutate(model = NULL)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM