Skip to content

Commit 9471b98

Browse files
committed
Ensure str_unique() always returns character.
1 parent 982ff70 commit 9471b98

File tree

2 files changed

+11
-6
lines changed

2 files changed

+11
-6
lines changed

R/unique.R

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -26,11 +26,11 @@ str_unique <- function(string, locale = "en", ignore_case = FALSE, ...) {
2626
ignore_case = ignore_case,
2727
...
2828
)
29-
out <- stri_unique(string, opts_collator = opts)
30-
# Preserve names of first occurrence for each unique value
31-
if (!is.null(names(string))) {
32-
idx <- match(out, string)
33-
names(out) <- names(string)[idx]
34-
}
29+
30+
# Ensure character output while preserving names of first occurrences
31+
string_chr <- as.character(string)
32+
keep <- !stringi::stri_duplicated(string_chr, opts_collator = opts)
33+
out <- string_chr[keep]
34+
names(out) <- names(string)[keep]
3535
out
3636
}

tests/testthat/test-unique.R

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,11 @@ test_that("can ignore case", {
77
expect_equal(str_unique(c("a", "A"), ignore_case = TRUE), "a")
88
})
99

10+
test_that("str_unique() returns NA_character_ for NA inputs", {
11+
expect_equal(str_unique(c(NA_character_, NA_character_)), NA_character_)
12+
expect_equal(str_unique(c(NA, NA)), NA_character_)
13+
})
14+
1015
test_that("str_unique() preserves names of first occurrences", {
1116
y <- c(A = "a", A2 = "a", B = "b")
1217
out <- str_unique(y)

0 commit comments

Comments
 (0)