I am trying to run a stratified analysis fitting a slightly different model in a particular strata using a nested data.frame and map mutate approach:
cars_nest <- mtcars %>%
group_by(cyl) %>%
nest()
model1 <- function(df) {
lm(mpg ~ disp + wt, data = df)
}
model2 <- function(df) {
lm(mpg ~ disp + wt + factor(vs), data = df)
}
cars_nest %>%
mutate(
model = case_when(
cyl == 8 ~ map(data, model1),
cyl %in% c(4, 6) ~ map(data, model2)
)
)
I'm getting the error
Error: Problem with
mutate()inputmodel. x contrasts can be applied only to factors with 2 or more levels ℹ Inputmodeliscase_when(...). ℹ The error occurred in group 3: cyl = 8.
I assume this is due to the vectorized operation of case_when as the below does seem to work.
cars_nest %>%
mutate(
model = ifelse(cyl == 8, map(data, model1),
ifelse(cyl %in% c(4, 6), map(data, model2), NA)
)
)
Is there a way to make this work using case_when()?
NOTE: the factor in model2 is necessary to replicate the issue. in the actual model, this is a factor that has only one level in the first strata and more than one level in the second strata.