Skip to content

Commit

Permalink
Explicitly return NA_integer_ when comparison includes NAs
Browse files Browse the repository at this point in the history
fixes #22
  • Loading branch information
joelnitta authored May 4, 2023
1 parent e291298 commit ff6012d
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
10 changes: 10 additions & 0 deletions R/utils.R
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,11 @@ count_higher <- function(x, y, na_rm = TRUE) {
# remove any NAs before making comparison
if (isTRUE(na_rm)) y <- y[!is.na(y)]

# or return NA_integer_ otherwise if y includes NA
if (!isTRUE(na_rm) && any(is.na(y))) {
return(NA_integer_)
}

# if comparison is zero length, return NA
if (length(y) == 0) {
return(NA_integer_)
Expand Down Expand Up @@ -60,6 +65,11 @@ count_lower <- function(x, y, na_rm = TRUE) {
# remove any NAs before making comparison
if (isTRUE(na_rm)) y <- y[!is.na(y)]

# or return NA_integer_ otherwise if y includes NA
if (!isTRUE(na_rm) && any(is.na(y))) {
return(NA_integer_)
}

# if comparison is zero length, return NA
if (length(y) == 0) {
return(NA_integer_)
Expand Down
4 changes: 2 additions & 2 deletions tests/testthat/test-utils.R
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ test_that("counting higher values works", {
expect_equal(count_higher(4, c(1:10, NA), na_rm = FALSE), NA_integer_)
expect_equal(count_higher(4, c(1:10, NaN)), 3)
expect_equal(count_higher(4, c(1:10, NaN), na_rm = FALSE), NA_integer_)
expect_equal(count_higher(4, vector("numeric", 0)), NaN)
expect_equal(count_higher(4, vector("numeric", 0)), NA_integer_)
})

test_that("counting lower values works", {
Expand All @@ -17,7 +17,7 @@ test_that("counting lower values works", {
expect_equal(count_lower(4, c(1:10, NA), na_rm = FALSE), NA_integer_)
expect_equal(count_lower(4, c(1:10, NaN)), 6)
expect_equal(count_lower(4, c(1:10, NaN), na_rm = FALSE), NA_integer_)
expect_equal(count_lower(4, vector("numeric", 0)), NaN)
expect_equal(count_lower(4, vector("numeric", 0)), NA_integer_)
})

# see
Expand Down

0 comments on commit ff6012d

Please sign in to comment.