I want to sort month names. When I use the strptime
function it returns an error as the attribute values only contains month names. When I use the sort
This is crude but if you wanted to make a function to sort or order rows by a month this would work:
sort.month <- function(x, dataframe = NULL, abbreviated = FALSE){
y <- data.frame(m1 = month.name, m2 = month.abb, n = 1:12)
z <- if(abbreviated) match(x, y[, 'm2']) else match(x, y[, 'm1'])
x <- if(is.null(dataframe)) x else dataframe
h <- data.frame(z, x)
h[order(z), ][, -1]
}
#examples
x <- sample(month.name, 20, r=T)
a<-data.frame(y= x, k =1:20, w=letters[1:20])
sort.month(a$y, a)
sort.month(a$y)
You could always convert your data to a factor. For example, suppose we have
x = c("January", "February", "March", "January")
then to convert to a factor, we have:
x_fac = factor(x, levels = month.name)
which on sorting gives:
R> sort(x_fac)
[1] January January February March
12 Levels: January February March April May June July August ... December