# How can I sort only some factors?

Hello community.

I want to sort factors but there are a lot of factors, so I want to use minimum effort.

How can I sort them like "factor(data, levels=c("A", "B", and the others))"?

Thank you.

`forcats::fct_other()` was designed exactly for this purpose.

``````library(forcats)
x <- factor(rep(LETTERS[1:9], times = c(40, 10, 5, 27, 1, 1, 1, 1, 1)))
fct_other(x, keep = c("A", "B"))

[1] A     A     A     A     A     A     A     A     A     A     A     A     A     A     A     A     A     A     A     A     A     A
[23] A     A     A     A     A     A     A     A     A     A     A     A     A     A     A     A     A     A     B     B     B     B
[45] B     B     B     B     B     B     Other Other Other Other Other Other Other Other Other Other Other Other Other Other Other Other
[67] Other Other Other Other Other Other Other Other Other Other Other Other Other Other Other Other Other Other Other Other Other
Levels: A B Other
``````
1 Like

But excuse me, maybe I couldn't explain well, I want to make first and second legend factor be in front of the other legends, and the other legends can line up randomly in line plot using ggplot.

How can I extract two legend factors from a lot of legends and place them at the top of the other legends and sort the rest so that they are in default alphabetical order?

Thank you.

Do you mean something like this?

``````library(forcats)

x <- factor(rep(LETTERS[1:9], times = c(40, 10, 5, 27, 1, 1, 1, 1, 1)))
fct_relevel(x, c("C", "I"))
#>  [1] A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A
#> [39] A A B B B B B B B B B B C C C C C D D D D D D D D D D D D D D D D D D D D D
#> [77] D D D D D D E F G H I
#> Levels: C I A B D E F G H
``````

Now levels `C` and `I` are before all others.

I could complete an easy-to-read line chart legend using the "fct_relevel" suggested by you two !

Thank you so much !

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.