Skip to content

Commit

Permalink
case_when support of NA values (tidyverse#2000)
Browse files Browse the repository at this point in the history
* case_when support of NA values

* case_when: handle NAs while populating output vector
  • Loading branch information
tjmahr authored and hadley committed Aug 24, 2016
1 parent 827b482 commit 9425d6e
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
2 changes: 1 addition & 1 deletion R/case_when.R
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ case_when <- function(...) {
out <- replace_with(
out, query[[i]] & !replaced, value[[i]],
paste0("RHS of case ", i, " (", deparse_trunc(f_rhs(formulas[[i]])), ")"))
replaced <- replaced | query[[i]]
replaced <- replaced | (query[[i]] & !is.na(query[[i]]))
}

out
Expand Down
12 changes: 12 additions & 0 deletions tests/testthat/test-case-when.R
Original file line number Diff line number Diff line change
Expand Up @@ -64,3 +64,15 @@ test_that("unmatched gets missing value", {
c(1, 2, NA)
)
})

test_that("missing values can be replaced (#1999)", {
x <- c(1:3, NA)
expect_equal(
case_when(
x <= 1 ~ 1,
x <= 2 ~ 2,
is.na(x) ~ 0
),
c(1, 2, NA, 0)
)
})

0 comments on commit 9425d6e

Please sign in to comment.