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))
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 ...
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.
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.
We can also sort in reverse order by using a minus sign ( – ) in front of the variable that we want sorted in reverse order.
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
Try this:
levels(dd$x) <- rev(unique(rev(dd$x)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With