Reputation: 2575
Here is a nested data.
df1 <- tibble::tribble(
~A, ~B, ~group,
4L, 1L, "A",
7L, 4L, "A",
NA_integer_, 1L, "B",
NA_integer_, 10L, "B")
df2 <- df1 %>% group_by(group) %>% nest()
I need to run lm using purrr:map.
map(df2$data, ~lm(A~B, data=.x))
What's the best way to find out which nested data encountered an error i.e. how can I know that group B has an issue.
Can you suggest a solution may be using purrr's possibly or safely?
Upvotes: 2
Views: 147
Reputation: 36086
You can use possibly()
here. In my example I have it return NA
if the model has an error.
First I make posslm
, using otherwise
to tell it what to return if there is an error after using lm
.
posslm = possibly(lm, otherwise = NA)
Then you can make a new column of models with map
in mutate
. Once that's done, filter
to NA
rows for the new variable and then pull out the group
.
mutate(df2, mod = map(data, ~posslm(A~B, data=.x))) %>%
filter( is.na(mod) ) %>%
pull(group)
[1] "B"
Upvotes: 5