Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Re-order numeric vector by name using custom order

Tags:

r

numeric

vector

I have a a numeric vector and want to re-order by name, using a custom order.

x <- sample(1:20, 5)
names(x) <- c("feb", "may", "mar", "jan", "apr")
x
feb may mar jan apr 
  7  10   5  13  11 

As you can see, the vectors are not in month order

Desired output

I wish to re-order this character vector through month order using the names, i.e. jan, feb, mar, apr, may...

How is this possible?

note: I am after a method that can be used on all names/character strings, rather than specifically date objects

like image 689
G. Gip Avatar asked Aug 21 '16 14:08

G. Gip


1 Answers

We can convert the names of 'x' to factor and settting the levels to the month.abb in lowercase, apply the order and get the 'x' in that order.

x[order(factor(names(x), levels=tolower(month.abb)))]
jan feb mar apr may 
 13  7   5  11  10 

The conversion to factor with levels specified can be applied to any character vector in a custom order, otherwise, by default, the ordering is based on alphabetical order i.e.

x[order(names(x))]

Suppose, if want the order to be say, 'jan', 'mar', 'apr', 'may', 'feb', use that as levels in the factor call

x[order(factor(names(x), levels = c('jan', 'mar', 'apr', 'may', 'feb')))]

As the OP posted another vector in a custom order in the comments

x1 <- c(icecream = 3, jelly = 4, fruit = 5)
x1[order(factor(names(x1), levels = c("jelly", "fruit", "icecream")))]
#   jelly    fruit icecream 
#      4        5        3 
like image 110
akrun Avatar answered Oct 06 '22 19:10

akrun