使用dplyr中的arrange()按时间顺序排序月份

使用dplyr中的arrange()按时间顺序排序月份,r,dplyr,R,Dplyr,我有一个将月份(数字)转换为名称的列表: fd <- df %>% select(product, sales, month) %>% mutate(month = month.name[month]) %>% filter(!is.na(product), sales!=0) %>% group_by(month) %>% summarise(sales = sum(sales)) %>% collect() 这种方法怎么样:

我有一个将月份(数字)转换为名称的列表:

fd <- df %>%
  select(product, sales, month) %>%
  mutate(month = month.name[month]) %>%
  filter(!is.na(product), sales!=0) %>%
  group_by(month) %>%
  summarise(sales = sum(sales)) %>%
  collect()

这种方法怎么样:

set.seed(12)
df <- data.frame(month = sample(12), x = LETTERS[1:12])
df
#   month x
#1      1 A
#2      9 B
#3     10 C
#4      3 D
#5      2 E
#6     12 F
#7      8 G
#8      4 H
#9      7 I
#10     5 J
#11    11 K
#12     6 L

library(dplyr)
df %>% 
   mutate(month = factor(month.name[month], levels = month.name)) %>% 
   arrange(month)

#       month x
#1    January A
#2   February E
#3      March D
#4      April H
#5        May J
#6       June L
#7       July I
#8     August G
#9  September B
#10   October C
#11  November K
#12  December F
set.seed(12)
df%
突变(月=因子(月.名称[月],级别=月.名称))%>%
安排(月)
#第x个月
#A.1.1
#2月2日E
#3月3日
#4月4日H
#J.5.5
#2006年6月6日
#7月7日一
#8月8日G
#B.9.9
#10月10日C
#11月11日K
#12月12日F
set.seed(12)
df <- data.frame(month = sample(12), x = LETTERS[1:12])
df
#   month x
#1      1 A
#2      9 B
#3     10 C
#4      3 D
#5      2 E
#6     12 F
#7      8 G
#8      4 H
#9      7 I
#10     5 J
#11    11 K
#12     6 L

library(dplyr)
df %>% 
   mutate(month = factor(month.name[month], levels = month.name)) %>% 
   arrange(month)

#       month x
#1    January A
#2   February E
#3      March D
#4      April H
#5        May J
#6       June L
#7       July I
#8     August G
#9  September B
#10   October C
#11  November K
#12  December F