Sorting months in R

后端 未结 2 2015
独厮守ぢ
独厮守ぢ 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)
    

提交回复
热议问题