Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to order the levels of factors according to the ordering of a data.frame (and not alphabetically)

Tags:

r

factors

Based on this question, I order a date.frame dd with two factors b and x

dd <- data.frame(b = factor(c("Hi", "Med", "Hi", "Low"), levels = c("Low", "Med", "Hi"), ordered = TRUE),
             x = factor(c("A", "D", "A", "C")), 
             y = c(8, 3, 9, 9),
             z = c(1, 1, 1, 2))

dd <- dd[with(dd, order(b, x)), ]
   b x y z
 Low C 9 2
 Med D 3 1
  Hi A 8 1
  Hi A 9 1

The order of the levels of dd$xdoes not reflect the actual order of dd$x but is alphabetical.

levels(dd$x)
[1] "A" "C" "D"

I would like the same order of levels as in the data.frame, i.e ,"C","D","A"

Of course I could do this

dd$x <- factor(dd$x, levels = c("C","D","A"))

but I need something general. I tried

dd$x <- factor(as.character(dd$x))

But the help state for the levels:

default is the unique set of values taken by as.character(x), sorted into increasing order of x.

How can I have a unique sef of value, that is "unsorted"?

I tried to understand the function factor and particularly the argument level factor but it's out of my limited understanding.

I found a solution but i couldn't apply it:

dd <- within(dd, x <- reorder(x, b))
like image 212
nebi Avatar asked Aug 02 '14 18:08

nebi


People also ask

How do you order levels in factor?

Using factor() function to reorder factor levels is the simplest way to reorder the levels of the factors, as here the user needs to call the factor function with the factor level stored and the sequence of the new levels which is needed to replace from the previous factor levels as the functions parameters and this ...

How do you change the order of factors in R?

One way to change the level order is to use factor() on the factor and specify the order directly. In this example, the function ordered() could be used instead of factor() . Another way to change the order is to use relevel() to make a particular level first in the list.

How do I sort a column by factor in R?

To sort a numerical factor column in an R data frame, we would need to column with as. character then as. numeric function and then order function will be used.

How do I sort in reverse order in R?

We can also sort in reverse order by using a minus sign ( – ) in front of the variable that we want sorted in reverse order.


2 Answers

This should be a general solution:

> factor(dd$x, as.character(unique(dd$x)))
[1] A D A C
Levels: A D C

Again, however, your example data do not seem to conform with what you describe as the intended result.

I guess you might also want:

> factor(dd$x, rev(as.character(unique(dd$x))))
[1] A D A C
Levels: C D A
like image 200
Thomas Avatar answered Nov 15 '22 05:11

Thomas


Try this:

levels(dd$x) <- rev(unique(rev(dd$x)))
like image 33
Robert Krzyzanowski Avatar answered Nov 15 '22 05:11

Robert Krzyzanowski