Sorting months in R

后端 未结 2 2018
独厮守ぢ
独厮守ぢ 2021-02-13 12:29

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

相关标签:
2条回答
  • 2021-02-13 13:03

    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)
    
    0 讨论(0)
  • 2021-02-13 13:06

    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
    
    0 讨论(0)
提交回复
热议问题