我有data.table
这样的
ds <- data.table(ID = c(1,1,1,1,1,2,2,2,2,2),
Month = c("Jan", "Feb", "Mar", "Apr", "May", "Jan", "Feb", "Mar", "Apr", "May"),
val = c(1,2,3,4,5,6,7,8,9,10))
ds
ID Month val
1: 1 Jan 1
2: 1 Feb 2
3: 1 Mar 3
4: 1 Apr 4
5: 1 May 5
6: 2 Jan 6
7: 2 Feb 7
8: 2 Mar 8
9: 2 Apr 9
10: 2 May 10
我希望我的data.table
在每个ID组中的位置,我重新排列Month
这样的订单
ID Month val
4: 1 Apr 4
5: 1 May 5
1: 1 Jan 1
2: 1 Feb 2
3: 1 Mar 3
9: 2 Apr 9
10: 2 May 10
6: 2 Jan 6
7: 2 Feb 7
8: 2 Mar 8
我想要每组,月份的顺序为Apr, May, Jan, Feb, Mar
我怎样才能做到这一点?
答案 0 :(得分:4)
我们可以使用自定义顺序中指定的order
将“月”转换为i
,从而使用factor
中的levels
ds[order(factor(Month, levels = c("Apr", "May", "Jan", "Feb", "Mar"))), .SD,ID]
# ID Month val
# 1: 1 Apr 4
# 2: 1 May 5
# 3: 1 Jan 1
# 4: 1 Feb 2
# 5: 1 Mar 3
# 6: 2 Apr 9
# 7: 2 May 10
# 8: 2 Jan 6
# 9: 2 Feb 7
#10: 2 Mar 8
或另一个选项是match
ds[order(match(Month, c("Apr", "May", "Jan", "Feb", "Mar"))), .SD,ID]
我们也可以使用month.abb
即month.abb[c(4:5, 1:3)]
来替换c("Apr", "May", "Jan", "Feb", "Mar")