Skip to content

Commit

Permalink
Fix case_when() logic error
Browse files Browse the repository at this point in the history
  • Loading branch information
hadley committed Jan 23, 2023
1 parent 6b92efb commit 707b332
Showing 1 changed file with 5 additions and 2 deletions.
7 changes: 5 additions & 2 deletions logicals.qmd
Original file line number Diff line number Diff line change
Expand Up @@ -488,6 +488,7 @@ It takes pairs that look like `condition ~ output`.
This means we could recreate our previous nested `if_else()` as follows:

```{r}
x <- c(-3:3, NA)
case_when(
x == 0 ~ "0",
x < 0 ~ "-ve",
Expand Down Expand Up @@ -538,13 +539,15 @@ flights |>
arr_delay < -30 ~ "very early",
arr_delay < -15 ~ "early",
abs(arr_delay) <= 15 ~ "on time",
arr_delay > 15 ~ "late",
arr_delay > 60 ~ "very late",
arr_delay < 60 ~ "late",
arr_delay < Inf ~ "very late",
),
.keep = "used"
)
```

Be wary when writing this sort of complex `case_when()` statement; my first two attempts used a mix of `<` and `>` and I kept accidentally creating overlapping conditions.

### Compatible types

Note that both `if_else()` and `case_when()` require **compatible** types in the output.
Expand Down

0 comments on commit 707b332

Please sign in to comment.