Home > Back-end >  pmap equivalent to map2 on 2 vars gives error when trying to pass args on to second function lm
pmap equivalent to map2 on 2 vars gives error when trying to pass args on to second function lm

Time:09-13

I am having a hard time using pmap. I would like to pass a model to pmap and then again to predict(). I am able to get what I need with map2 but I want to know how to do this with pmap.

# r 4.1, native pipe has no _ placeholder
library(tidyverse)
diamonds |> 
  group_by(cut, color) |> 
  nest() |> 
  mutate(
    mod.lm = map(data, ~ lm(price ~ depth, data = .x)),
    
    # map2 works, I want to just do the same with pmap
    #test_data = map2(data, mod.lm, ~ .x |> mutate(prediction_lm = predict(object = .y))) # works
    test_data = pmap(list(data, mod.lm), function(x, y) x |> mutate(prediction_lm = predict(object = y)))
  )

Gives error:

Error: Problem with mutate() column test_data. ℹ test_data = pmap(list(data, mod.lm), function(x, y) mutate(x, prediction_lm = predict(object = y))). x Problem with mutate() column prediction_lm. ℹ prediction_lm = predict(object = y). x no applicable method for 'predict' applied to an object of class "c('double', 'numeric')"

How can I pass mod.lm to predict within pmap()?

CodePudding user response:

The issue is that y is the name of a column of the diamonds dataset. Hence, when doing mutate(prediction_lm = predict(object = y)) the y column is passed to predict instead of the model object you passed as argument. To fix that you could use the .env pronoun from rlang:

library(tidyverse)

diamonds |>
  group_by(cut, color) |>
  nest() |>
  mutate(
    mod.lm = map(data, ~ lm(price ~ depth, data = .x)),
    test_data = pmap(list(data, mod.lm), function(x, y) x |> mutate(prediction_lm = predict(object = .env$y)))
  )
#> # A tibble: 35 × 5
#> # Groups:   cut, color [35]
#>    cut       color data                 mod.lm test_data           
#>    <ord>     <ord> <list>               <list> <list>              
#>  1 Ideal     E     <tibble [3,903 × 8]> <lm>   <tibble [3,903 × 9]>
#>  2 Premium   E     <tibble [2,337 × 8]> <lm>   <tibble [2,337 × 9]>
#>  3 Good      E     <tibble [933 × 8]>   <lm>   <tibble [933 × 9]>  
#>  4 Premium   I     <tibble [1,428 × 8]> <lm>   <tibble [1,428 × 9]>
#>  5 Good      J     <tibble [307 × 8]>   <lm>   <tibble [307 × 9]>  
#>  6 Very Good J     <tibble [678 × 8]>   <lm>   <tibble [678 × 9]>  
#>  7 Very Good I     <tibble [1,204 × 8]> <lm>   <tibble [1,204 × 9]>
#>  8 Very Good H     <tibble [1,824 × 8]> <lm>   <tibble [1,824 × 9]>
#>  9 Fair      E     <tibble [224 × 8]>   <lm>   <tibble [224 × 9]>  
#> 10 Ideal     J     <tibble [896 × 8]>   <lm>   <tibble [896 × 9]>  
#> # … with 25 more rows
  • Related