【问题标题】:R: Parse date as year/quarterR:将日期解析为年/季度
【发布时间】: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 变量中提取这些变量。

通过zoolubridate 可以解决这个问题,但我希望有人能告诉我为什么我的函数不起作用

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


    【解决方案1】:

    您的解决方案忽略了 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
    

    【讨论】:

    • 感谢您提供非常有用的解释和替代解决方案!我对您实现这一目标的方式以及 lubridate 和 zoo 等软件包提供的各种其他方式感到满意。有没有办法以某种方式修改我的功能,以便它执行所需的操作?例如,我是否需要将“if”语句包装在某种 for 循环中以便对函数进行矢量化?
    猜你喜欢
    • 1970-01-01
    • 2014-03-01
    • 1970-01-01
    • 2015-09-13
    • 2019-11-18
    • 2016-10-28
    • 1970-01-01
    • 2021-07-26
    • 1970-01-01
    相关资源
    最近更新 更多