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$x
does 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))