在 tidyverse 中按时间顺序对月份名称进行排序

Sorting Month names chronologically in the tidyverse

所以我已经阅读了很多方法,可以在基本 R 中或通过 tidyverse 方法按名称对月份进行排序,但所有方法都需要用户定义的函数和/或一些非常冗长的语言。

这是一个例子: Sorting month chronologicaly with arrange() from dplyr

这是几乎所有涉及日期或时间的分析的基本需求。当然,必须有一个函数,例如带有 "calendar"(可能还有 descd-calendar)参数的 arrange()。或者我错过了什么?

可能会根据他们在month.name的位置排列,可以用match(months, month.name)?

找到
df <- data.frame(months = sample(month.name, 5))
df
#     months
#1 September
#2      July
#3  December
#4  February
#5   January

df %>% arrange(match(months, month.name))
#     months
#1   January
#2  February
#3      July
#4 September
#5  December

您可以将它们转换为 Date,然后对它们进行排序。

library(anydate); library(dplyr);
c('January', 'February', 'December', 'June') %>% anydate %>% sort 

如果您想将它们保留为字符串,您可以使用 Psidom 的方法或执行

c('January', 'February', 'December', 'June') %>% (function(x) x[x %>% anydate %>% order])