【问题标题】:Tsibble year week function returns in undesired behaviourTsibble 年周函数返回不良行为
【发布时间】:2020-05-22 05:35:23
【问题描述】:

我尝试使用tsibble 将缺少值的日期列转换为年-周格式。这样做会返回解析失败或数值结果。

最终输出应如下所示:2020 W1, 2020 W6。

有没有办法使用tsibble 包解决这个问题?奇怪的是,这个包的 yearmonth 函数也适用于 NA 和空值。

library(tsibble)
library(lubridate)

x <- c("2020-01-01", "", "2020-02-06")

yearweek(x)
# Output: fails

ifelse(x == "", "", yearweek(ymd(x)))
# Output: "18260" "" "18295"

# Desired Output: "2020 W1", "", "2020 W6".

【问题讨论】:

    标签: r date lubridate tsibble


    【解决方案1】:

    您可以在基础 R 中执行此操作:

    format(as.Date(x), "%Y W%V")
    #[1] "2020 W01" NA         "2020 W06"
    

    当你在yearweek 中从tsibble 中使用它时,它会返回一个错误

    library(tsibble)
    yearweek(as.Date(x))
    

    yrs[mth_wk == "12_01"]

    由于yearweek 函数返回类"yearweek" "Date" 的输出,因此它不允许其中包含NA 值或空值(""),因为它们不属于"yearweek" "Date" 类。一个技巧是将值更改为字符。

    x1 <- as.Date(x)
    inds <- !is.na(x1)
    x2 <- character(length = length(x1))
    x2[inds] <- as.character(yearweek(x1[inds]))
    x2
    #[1] "2020 W01" ""         "2020 W06"
    

    【讨论】:

    • 谢谢!这确实解决了我的问题,完全忽略了基本的 R 解决方案。知道为什么这个 yearweek 函数不能按预期工作吗?
    • @rkraft 我添加了一些解释和使yearweek 工作的方法。
    猜你喜欢
    • 2013-02-11
    • 1970-01-01
    • 2020-03-06
    • 2021-09-18
    • 1970-01-01
    • 1970-01-01
    • 2019-07-27
    • 2021-01-18
    • 1970-01-01
    相关资源
    最近更新 更多