我想将数据表中的月份名称(Jan,Feb等)的矢量转换为它们的数字等价物(1,2,...)。代码
which(month.abb == month)
按预期工作;即which(month.abb == "Feb")
返回2.但是数据表中使用的相同代码会返回警告以及包含不符合我预期的数字的test
向量。
dt <- data.table(month = sort(c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")))
dt[, test := which(month.abb == month)]
答案 0 :(得分:2)
试试这个:
dt[, test := match(month, month.abb)]
你会得到: -
month test
1: Apr 4
2: Apr 4
3: Aug 8
4: Aug 8
5: Dec 12
6: Dec 12
7: Feb 2
8: Feb 2
9: Jan 1
10: Jan 1
11: Jul 7
12: Jul 7
13: Jun 6
14: Jun 6
15: Mar 3
16: Mar 3
17: May 5
18: May 5
19: Nov 11
20: Nov 11
21: Oct 10
22: Oct 10
23: Sep 9
24: Sep 9
答案 1 :(得分:0)
只需使用矢量化查找表:
month_trans <- setNames(1:12, month.abb)
set.seed(2017-11-15)
month_column <- sample(month.abb, 50, replace=TRUE)
month_column
## [1] "Feb" "Mar" "Jan" "Jul" "Oct" "Aug" "Oct" "Aug" "May" "Jan" "Aug" "Apr" "Jan" "May"
## [15] "May" "Mar" "Dec" "Oct" "Nov" "Nov" "Aug" "Jul" "Mar" "Feb" "Oct" "Feb" "Feb" "Dec"
## [29] "Dec" "Sep" "Nov" "May" "Jan" "Oct" "Feb" "Oct" "Nov" "Feb" "Mar" "Mar" "Nov" "Jun"
## [43] "May" "Mar" "Jul" "Nov" "Jul" "Dec" "Oct" "Feb"
month_trans[month_column]
## Feb Mar Jan Jul Oct Aug Oct Aug May Jan Aug Apr Jan May May Mar Dec Oct Nov Nov Aug Jul
## 2 3 1 7 10 8 10 8 5 1 8 4 1 5 5 3 12 10 11 11 8 7
## Mar Feb Oct Feb Feb Dec Dec Sep Nov May Jan Oct Feb Oct Nov Feb Mar Mar Nov Jun May Mar
## 3 2 10 2 2 12 12 9 11 5 1 10 2 10 11 2 3 3 11 6 5 3
## Jul Nov Jul Dec Oct Feb
## 7 11 7 12 10 2
unname(month_trans[month_column])
## [1] 2 3 1 7 10 8 10 8 5 1 8 4 1 5 5 3 12 10 11 11 8 7 3 2 10 2 2 12
## [29] 12 9 11 5 1 10 2 10 11 2 3 3 11 6 5 3 7 11 7 12 10 2