lost
lost

Reputation: 1669

throw an error inside a case_when()

I have a case_when() inside a mutate() and I'd like R to stop and throw an error if the TRUE condition is fulfilled. This is for debugging purposes.

For example, values for mtcars$cyl are 4, 6 or 8. With the proper solution in place in the fourth line, this should be able to run without error:

mtcars %>%
  mutate(test = case_when(
    cyl > 3 ~ "ok",
    TRUE ~ # code for throwing error here
  ))

This should throw the error:

mtcars %>%
  mutate(test = case_when(
    cyl < 3 ~ "ok",
    TRUE ~ # code for throwing error here
  ))

I tried stop but this triggers the exception even if TRUE is never fulfilled.

Upvotes: 4

Views: 736

Answers (1)

moodymudskipper
moodymudskipper

Reputation: 47320

You can't do it in the case_when call as far as I understand, because all RHSs will be evaluated beforehand to make sure they're of the same type.

You could do this however :

mtcars %>%
  mutate(test = case_when(
    cyl > 3 ~ "ok",
    TRUE ~ NA_character_
  ),
  test=if (anyNA(test)) stop() else test
  )

or

mtcars %>%
  mutate(test = case_when(
    cyl > 3 ~ "ok",
    TRUE ~ "STOP_VALUE"
  ),
  test=if ("STOP_VALUE" %in% test) stop() else test
  )

Upvotes: 2

Related Questions