我正在使用data.table,尝试创建一个名为“season”的新列,根据名为“MonthName”的列生成对应的季节,例如夏季、冬季等。
我想知道是否有更有效的方法基于月份值向数据表中添加一个季节列。
以下是300,000个观察结果中的前6个,请假设表名为“dt”。
rrp Year Month Finyear hourminute AvgPriceByTOD MonthName
1: 35.27500 1999 1 1999 00:00 33.09037 Jan
2: 21.01167 1999 1 1999 00:00 33.09037 Jan
3: 25.28667 1999 2 1999 00:00 33.09037 Feb
4: 18.42334 1999 2 1999 00:00 33.09037 Feb
5: 16.67499 1999 2 1999 00:00 33.09037 Feb
6: 18.90001 1999 2 1999 00:00 33.09037 Feb
我尝试了以下代码:
dt[, Season := ifelse(MonthName = c("Jun", "Jul", "Aug"),"Winter", ifelse(MonthName = c("Dec", "Jan", "Feb"), "Summer", ifelse(MonthName = c("Sep", "Oct", "Nov"), "Spring" , ifelse(MonthName = c("Mar", "Apr", "May"), "Autumn", NA))))]
返回结果:
rrp totaldemand Year Month Finyear hourminute AvgPriceByTOD MonthName Season
1: 35.27500 1999 1 1999 00:00 33.09037 Jan NA
2: 21.01167 1999 1 1999 00:00 33.09037 Jan Summer
3: 25.28667 1999 2 1999 00:00 33.09037 Feb Summer
4: 18.42334 1999 2 1999 00:00 33.09037 Feb NA
5: 16.67499 1999 2 1999 00:00 33.09037 Feb NA
6: 18.90001 1999 2 1999 00:00 33.09037 Feb Summer
我遇到了错误:
Warning messages:
1: In MonthName == c("Jun", "Jul", "Aug") :
longer object length is not a multiple of shorter object length
2: In MonthName == c("Dec", "Jan", "Feb") :
longer object length is not a multiple of shorter object length
3: In MonthName == c("Sep", "Oct", "Nov") :
longer object length is not a multiple of shorter object length
4: In MonthName == c("Mar", "Apr", "May") :
longer object length is not a multiple of shorter object length
同时,由于我不知道的原因,其中一些夏季月份被正确地标记为“夏季”,但其他月份则被标记为NA。例如,第1行和第2行都应该是夏季,但返回的结果不同。
提前感谢!
MonthName %in% c("Jun",...)
而不是=
。 - SymbolixAUcut
函数:droplevels(cut(dt$Month, breaks = c(0, 2, 5, 8, 11, 13), labels = c('冬季', '春季', '夏季', '秋季', '冬季')))
. - alistaire