Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fct_unique() drops NA data if it isn't an explicit level #293

Closed
DavisVaughan opened this issue Dec 16, 2021 · 0 comments · Fixed by #328
Closed

fct_unique() drops NA data if it isn't an explicit level #293

DavisVaughan opened this issue Dec 16, 2021 · 0 comments · Fixed by #328
Labels
bug an unexpected problem or unintended behavior help wanted ❤️ we'd love your help!
Milestone

Comments

@DavisVaughan
Copy link
Member

This came up as an issue in tidyr (tidyverse/tidyr#1275, tidyverse/tidyr#1276).

library(forcats)

x <- factor(c(NA, "x"))

fct_unique(x)
#> [1] x
#> Levels: x

# Retains NA data at the end without adding a new factor level
x <- factor(c(NA, "x"))
tidyr:::fct_unique(x)
#> [1] x    <NA>
#> Levels: x

# If an NA factor level already existed, doesn't change the level position
x <- factor(levels = c(NA, "x"), exclude = NULL)
tidyr:::fct_unique(x)
#> [1] <NA> x   
#> Levels: <NA> x

We could use the tidyr implementation here:

fct_unique <- function(x) {
   if (!is.factor(x)) {
     abort("`x` must be a factor.")
   }

   levels <- levels(x)
   out <- levels

   if (!anyNA(levels) && anyNA(x)) {
     out <- c(out, NA_character_)
   }

   factor(out, levels = levels, exclude = NULL, ordered = is.ordered(x))
 }
@hadley hadley added bug an unexpected problem or unintended behavior help wanted ❤️ we'd love your help! labels Mar 2, 2022
@hadley hadley added this to the v1.0.0 milestone Jan 3, 2023
hadley added a commit that referenced this issue Jan 3, 2023
* Make purpose more clear in docs. Fixes #284.
* Include implicit NA if present. Fixes #293.
@hadley hadley closed this as completed in 25f3fb7 Jan 4, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug an unexpected problem or unintended behavior help wanted ❤️ we'd love your help!
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants