我的 R 数据框列中的日期格式为 WK01Q32014
字符串。
我想将每个日期转换为 Date()
对象。
因此我更改了格式,使其看起来像 01-3-2014
。例如,我想尝试执行 as.Date("01-3-2014","%W-%Q-%Y")
之类的操作,但是没有季度的格式代码我知道。
有没有办法使用lubridate
、zoo
或任何其他库来做到这一点?
最佳答案
我不知道任何具体功能,但这是一个基本功能:
convert_WQ_to_Date <- function(D) {
weeks <- as.integer(substr(D, 3, 4))
quarter <- as.integer(substr(D, 6, 6))
year <- substr(D, 7, 10)
days <- 7 * ((quarter - 1) * 13 + (weeks-1))
as.Date(sprintf("%s-01-01", year)) + days
}
示例
D <- c("WK01Q32014", "WK01Q12014", "WK05Q42014", "WK01Q22014", "WK02Q32014")
convert_WQ_to_Date(D)
[1] "2014-07-02" "2014-01-01" "2014-10-29" "2014-04-02" "2014-07-09"
关于r - 将包含周和季度的日期字符串格式化为 Date 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26151418/