tidyverse / forcats

🐈🐈🐈🐈: tools for working with categorical variables (factors)
https://forcats.tidyverse.org/
Other
554 stars 126 forks source link

`fct_reorder2()` drops values #348

Open hadley opened 1 year ago

hadley commented 1 year ago
library(forcats)
library(dplyr, warn.conflicts = FALSE)

by_age <- gss_cat |>
  count(age, marital) |>
  group_by(age) |>
  mutate(
    prop = n / sum(n)
  )

nrow(by_age)
#> [1] 357
with(by_age, length(fct_reorder2(marital, age, prop, .na_rm = TRUE)))
#> [1] 351
with(by_age, length(fct_reorder2(marital, age, prop)))
#> Warning: `fct_reorder2()` removing 6 missing values.
#> ℹ Use `.na_rm = TRUE` to silence this message.
#> ℹ Use `.na_rm = FALSE` to preserve NAs.
#> [1] 351

Created on 2023-02-27 with reprex v2.0.2

DanChaltiel commented 6 months ago

Note that the warning is not thrown inside a mutate call:

library(forcats)
library(dplyr, warn.conflicts = FALSE)

by_age <- gss_cat |>
  count(age, marital) |>
  mutate(
    prop = n / sum(n), 
    .by = age
  )

by_age |>
  mutate(m = fct_reorder2(marital, age, prop)) |>
  nrow()
#> Error in `mutate()`:
#> ℹ In argument: `m = fct_reorder2(marital, age, prop)`.
#> Caused by error:
#> ! `m` must be size 357 or 1, not 351.

by_age |>
  mutate(m = fct_reorder2(marital, age, prop, .na_rm = FALSE)) |>
  nrow()
#> [1] 357

Created on 2024-05-14 with reprex v2.1.0