我有一个看起来像这样的数据框
Classes ‘tbl_df’, ‘tbl’ and 'data.frame': 344479 obs. of 6 variables:
$ REGION : chr "NSW1" "NSW1" "NSW1" "NSW1" ...
$ SETTLEMENTDATE: POSIXct, format: "1998-12-07 02:00:00" "1998-12-07
02:30:00" "1998-12-07 03:00:00" "1998-12-07 03:30:00" ...
$ TOTALDEMAND : num 3294 5337 5296 5266 5330 ...
$ RRP : num 8.01 11.16 13.52 12.52 13.01 ...
$ PERIODTYPE : chr "TRADE" "TRADE" "TRADE" "TRADE" ...
$ month : num 12 12 12 12 12 12 12 12 12 12 ...
我试图通过从year_quarter
变量中提取这些变量来创建一个2014-Q1
变量,该变量是一个字符串并具有以下形式:SETTLEMENTDATE
(表示年/季)。
通过zoo
或lubridate
有很多解决这个问题的方法,但是我希望有人可以告诉我为什么我的功能不起作用:
quarter_fun <- function(df){
df$quarter <- NA
if (df$month <= 3){
df$quarter <- paste(format(df$SETTLEMENTDATE, format = "%Y")[1],
"Q1", sep="-")
} else if (df$month >= 4 & df$month <= 6){
df$quarter <- paste( format(df$SETTLEMENTDATE, format = "%Y")[1],
"Q2", sep="-")
} else if (df$month >= 7 & df$month <= 9){
df$quarter <- paste(format(df$SETTLEMENTDATE, format = "%Y")[1],
"Q3", sep="-")
} else if (df$month == 10){
df$quarter <- paste(format(df$SETTLEMENTDATE, format = "%Y")[1],
"Q4", sep="-")
}
}
我收到此错误消息:
the condition has length > 1 and only the first element will be usedthe
condition has length > 1 and only the first element will be usedthe
condition has length > 1 and only the first element will be usedthe
condition has length > 1 and only the first element will be used
任何帮助都将非常感激 - 再次,这不是关于找到手头任务的解决方案,而是关于理解为什么我的尝试不起作用,因为在我的路上某处有明显错误的假设(或几个) 。
谢谢!
你的解决方案忽略了df$month
是一个向量的事实,而if
需要评估一个真/假值。您的比较产生了真/假值的逻辑向量。因此警告消息“仅使用第一个元素”。
相反,请考虑使用cut
重新标记数字月份:
numeric.months <- 1:12
quarters <- cut(numeric.months, seq(0, 12, 3), labels = paste0('Q', 1:4), include.lowest = T)
[1] Q1 Q1 Q1 Q2 Q2 Q2 Q3 Q3 Q3 Q4 Q4 Q4
Levels: Q1 Q2 Q3 Q4