Skip to content

Incorrect results of fct_reorder() with a character vector and duplicates #387

@DanChaltiel

Description

@DanChaltiel

Hi,

I encountered an unexpected result with fct_reorder() when .x is not numeric and .f has duplicates:

  • If .x is a character, the result is incorrect and there is a warning
  • If .x is a factor, there is an unexpected error.
f = c("a", "b", "b")
x = c(3,2,1)

#This is OK
forcats::fct_reorder(f, x)
#> [1] a b b
#> Levels: b a

x = c("z", "x", "y")
forcats::fct_reorder(f, x)
#> Warning in mean.default(sort(x, partial = half + 0L:1L)[half + 0L:1L]):
#> argument is not numeric or logical: returning NA
#> [1] a b b
#> Levels: a b

x = factor(c("z", "x", "y"))
forcats::fct_reorder(f, x)
#> Error in median.default(x, ...): need numeric data

#This is OK
x = as.numeric(factor(c("z", "x", "y")))
forcats::fct_reorder(f, x)
#> [1] a b b
#> Levels: b a

Created on 2025-12-02 with reprex v2.1.1

Reordering a factor by another categorical variable is an important feature that has proven very useful in my work.

Thanks a lot for maintaining this great package.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions