Skip to content

I hate manipulating the order of factor levels in R

November 21, 2012

For some reason that’s probably a short-coming of my brain, it always takes me longer than it should to manipulate the order of factor levels. My head just has trouble with relevel, reorder, etc… So I’ve written a function that works with my brain better:

reorder2 <- function(x, X){
	X <- rev(X)
	for(i in seq_along(X)) x <- relevel(x, X[i])

x is a factor and X is a character vector of levels in the order in which you want them to be in x. So for example,

> levels(fac)
[1] "arctic"      "equatorial"  "midlatitude" "subarctic"   "subtropical"
[6] "tropical"

That’s not right! I want this more reasonable order,

> cor.ord <- c('equatorial','tropical','subtropical','midlatitude','subarctic','arctic')

So I pass it to reorder2,

> fac <- reorder2(fac, cor.ord)

And now everything’s fine,

> levels(fac)
[1] "equatorial"  "tropical"    "subtropical" "midlatitude" "subarctic"  
[6] "arctic"
One Comment leave one →
  1. November 28, 2012 1:01 pm

    reorder does my head in from time to time as well. Here are a couple of other alternatives:

    fac <- factor(fac, levels=cor.ord)
    reorder2 <- function(x, X) reorder(x, match(x, X))

    I’m not sure if the first might also have some drawbacks (e.g. customised labels reverting to level names).

    The second uses your x and X, uses match() to find the position of each element of x in X, and then uses this vector of positions to define the new level positions. That said, if the code you’ve written works and makes sense to you, then there’s nothing wrong with that 😉

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: