【发布时间】:2018-09-01 21:43:16
【问题描述】:
我有一个看起来像这样的数据框
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
任何帮助都将不胜感激 - 这不是为了找到手头任务的解决方案,而是为了理解为什么我的尝试不起作用,因为我的某处显然有一个错误的假设(或几个)一路走来。
谢谢!
【问题讨论】:
标签: r function functional-programming zoo lubridate