I am trying to reorder a factor data type so that when I plot stats
associated with the factor, the ordering makes sense.

For instance, if I have a factor entered as follows ...

A = as.factor(c("1", "10", "3", "3", "10", "10"))

levels(A)


... the ordering does not really make sense (assuming I want the factor
ordered by integer value), but I understand that this "mis-ordering"  is
because the ordering is based on a character string data type and not on an
integer data type.  Because I run into this problem frequently, I wrote a
small function to fix this:


reorder_factor = function(x, x_sum, decreasing=FALSE){

factor(as.character(x), levels=levels(x)[order(x_sum, decreasing=decreasing)
])

}


I can then run the following code to fix the problem:


A = reorder_factor(x=A, x_sum=as.numeric(levels(A)), decreasing=FALSE)

levels(A)


... and now I have correctly ordered integers.  Perhaps not the most elegant
solution, but it worked for my purposes.  Now I have a more complicated
problem and I need help.  Assuming the following factor:


B = as.factor(c("Engine 1", "Engine 10", "Ladder 3", "Engine 3", "Ladder 10",
"Engine 10"))

levels(B)


I would like the factor ordered first by the proceeding unit type and then
ordered by the following integer.  In this case, I would like to see this
order:  Engine 1, Engine 3, Engine 10, Ladder 3, Ladder 10.  I have tried
many different ways of separating out the unit type from the number, but am
having trouble figuring out a good way of achieving this factor order.  For
such a small example, I could obviously manually change the order, but I am
dealing with much larger datasets with many unit types and up to 20
different numbers for each unit type.  Having an automated way of ordering
these units would be a huge help.  Thanks in advance for any help you can
provide.

--Markus Weisner

        [[alternative HTML version deleted]]

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to