Pass args from map to predict gets error 'must be size 148 not 1'

Code block:

# r 4.1, native pipe has no _ placeholder
diamonds |> 
  group_by(cut, color) |> 
  nest() |> 
  crossing(bla = c(0.1, 0.5, 0.6)) |> 
  mutate(
    mod.lm = map(data, ~ lm(price ~ depth, data = .x)),
    test_data = pmap(list(data, mod.lm, bla), function(.a, .b, .c) {.a |> filter(carat >= .c) |> mutate(prediction_lm = predict(object = .b))})
  )

I am trying to pass params from purr::map through to filter and then mutate. I.e. I want to add a prediction to a subset of data, where nested data frame data is first filtered before being passed to predict, along with the model mod.lm in the previous mutate line (.a |> filter(carat >= .c))

The above code block gives error:

Error: Problem with mutate() column test_data. :information_source: test_data = pmap(...). x Problem with mutate() column prediction_lm. :information_source:
prediction_lm = predict(object = .b). :information_source: prediction_lm must be size
148 or 1, not 163.

How can I create a new data frame via pmap() where I pass in args mod.lm, the data data and field bla to filter with?

I don't see a need to use any maps here

diamonds |>
  group_by(cut, color) |>
  nest() |>
  crossing(bla = c(0.1, 0.5, 0.6)) |>
  rowwise() |>
  mutate(
    mod.lm = list(lm(price ~ depth, data = data)),
    filtered_data = list(
      filter(
        data,
        carat >= bla
      )
    ),
    test_data = list(
      mutate(filtered_data,
        prediction_lm = predict(
          object = mod.lm,
          newdata = filtered_data
        )
      )
    )
  ) |>  ungroup()  # |> select(-filtered_data) ### clean up if you want

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.