using lm in list column to predict new values using purrr

前端 未结 1 1506
无人共我
无人共我 2020-12-06 03:36

I am trying to add a column of predictions to a dataframe that has a list column that contains an lm model. I adopted some of the code from this post.

I have made a

相关标签:
1条回答
  • 2020-12-06 04:25

    You could take advantage of the newdata argument to predict.

    I use map2_dbl so it returns just the single value rather than a list.

    mutate(Pred = map2_dbl(model, 1:5, ~predict(.x, newdata = data.frame(ind = .y))))
    
    # A tibble: 5 x 4
      groups         the_data    model       Pred
      <fctr>           <list>   <list>      <dbl>
    1      A <tibble [5 x 2]> <S3: lm> -0.4822045
    2      B <tibble [5 x 2]> <S3: lm> -0.1357712
    3      C <tibble [5 x 2]> <S3: lm> -0.2455760
    4      D <tibble [5 x 2]> <S3: lm>  0.4818425
    5      E <tibble [5 x 2]> <S3: lm> -0.3473236
    

    If you add ind to the dataset before prediction you can use that column instead of 1:5.

    mutate(ind = 1:5) %>%
        mutate(Pred = map2_dbl(model, ind, ~predict(.x, newdata = data.frame(ind = .y) )))
    
    # A tibble: 5 x 5
      groups         the_data    model   ind       Pred
      <fctr>           <list>   <list> <int>      <dbl>
    1      A <tibble [5 x 2]> <S3: lm>     1 -0.4822045
    2      B <tibble [5 x 2]> <S3: lm>     2 -0.1357712
    3      C <tibble [5 x 2]> <S3: lm>     3 -0.2455760
    4      D <tibble [5 x 2]> <S3: lm>     4  0.4818425
    5      E <tibble [5 x 2]> <S3: lm>     5 -0.3473236
    
    0 讨论(0)
提交回复
热议问题