【发布时间】:2012-03-19 11:49:19
【问题描述】:
我想对月份名称进行排序。当我使用 strptime 函数时,它会返回错误,因为属性值仅包含月份名称。当我使用sort 函数时,月份按字母顺序排序。
【问题讨论】:
我想对月份名称进行排序。当我使用 strptime 函数时,它会返回错误,因为属性值仅包含月份名称。当我使用sort 函数时,月份按字母顺序排序。
【问题讨论】:
您始终可以将数据转换为因子。例如,假设我们有
x = c("January", "February", "March", "January")
然后转换为一个因子,我们有:
x_fac = factor(x, levels = month.name)
排序后给出:
R> sort(x_fac)
[1] January January February March
12 Levels: January February March April May June July August ... December
【讨论】:
month.name 和 month.abb 在这方面很有用,因此您无需输入月份名称等。不过,仅对英文月份名称和缩写有用。
month.name
这是粗略的,但如果你想创建一个按月对行进行排序或排序的函数,这将起作用:
sort.month <- function(x, dataframe = NULL){
y <- data.frame(m1 = month.name, m2 = month.abb, n = 1:12)
z <- if(max(nchar(x)) == 3) 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)
【讨论】: