Wooheon
Wooheon

Reputation: 339

Difference of fct_reorder and reorder

This is an exmaple of fct_reorder

boxplot(Sepal.Width ~ fct_reorder(Species, Sepal.Width, .desc = TRUE), data = iris) enter image description here

This code is identical with boxplot(Sepal.Width ~ reorder(Species, -Sepal.Width), data = iris)

What is the better point fct_reorder() than reorder()?

Upvotes: 2

Views: 826

Answers (1)

Steen Harsted
Steen Harsted

Reputation: 1932

The two functions are very similar, but have a few differences:

  • reorder() works with atomic vectors and defaults to using mean().
  • fct_reorder() only works with factors (or character vectors) and defaults to using median()

Example:

library(forcats)

x <-  1:10
xf <- factor(1:10)
y <-  10:1

reorder(x, y)
#>  [1] 1  2  3  4  5  6  7  8  9  10
#> attr(,"scores")
#>  1  2  3  4  5  6  7  8  9 10 
#> 10  9  8  7  6  5  4  3  2  1 
#> Levels: 10 9 8 7 6 5 4 3 2 1

reorder(xf, y)
#>  [1] 1  2  3  4  5  6  7  8  9  10
#> attr(,"scores")
#>  1  2  3  4  5  6  7  8  9 10 
#> 10  9  8  7  6  5  4  3  2  1 
#> Levels: 10 9 8 7 6 5 4 3 2 1

fct_reorder(x, y) 
#> Error: `f` must be a factor (or character vector).

fct_reorder(xf, y)
#>  [1] 1  2  3  4  5  6  7  8  9  10
#> Levels: 10 9 8 7 6 5 4 3 2 1

Created on 2022-01-07 by the reprex package (v2.0.1)

Upvotes: 0

Related Questions