-2

I have a column that looks like this:

 $ Stage     : chr  "final" "final" "final" "final" ...

The values are final, first, resub.

I want to convert it into a factor, specifically ordered like this:

first, resub, final

Why that order? Because I use it in a ggplot later and they are displaying in the wrong order.

M--
  • 25,431
  • 8
  • 61
  • 93
pitosalas
  • 10,286
  • 12
  • 72
  • 120

1 Answers1

0

As far as I know you can also convert to factor and order as you want in one of the layers in ggplot() function but it can be done earlier. Everything is easier with dplyr.

>str(mydf$anim3) # one column from my df 
 chr [1:5] "A" "A" "B" "C" "C"

>mydf <- mydf %>% mutate_if(is.character,as.factor)
>str(mydf$anim3)
 Factor w/ 3 levels "A","B","C": 1 1 2 3 3

>levels(mydf3$anim3) #order of our levels
 [1] "A" "B" "C"

>str(factor(mydf$anim3,levels(mydf3$anim3)[c(3,1,2)])) #you can order levels whatever you want using this
 Factor w/ 3 levels "C","A","B": 2 2 3 1 1
Adamm
  • 2,150
  • 22
  • 30