4
votes

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))
2
The order of levels according to your example data is A D C, not D A C. - Thomas
Right i mean "C" "D" "A" - nebi

2 Answers

10
votes

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
2
votes

Try this:

levels(dd$x) <- rev(unique(rev(dd$x)))