using lm in list column to predict new values using purrr

前端 未结 1 1505
无人共我
无人共我 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
                          
    1      A   -0.4822045
    2      B   -0.1357712
    3      C   -0.2455760
    4      D    0.4818425
    5      E   -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
                           
    1      A       1 -0.4822045
    2      B       2 -0.1357712
    3      C       3 -0.2455760
    4      D       4  0.4818425
    5      E       5 -0.3473236
    

    0 讨论(0)
提交回复
热议问题