【问题标题】:Change date to the last day of month using days_in_month [duplicate]使用 days_in_month [重复] 将日期更改为每月的最后一天
【发布时间】:2021-04-10 17:07:57
【问题描述】:

我有一个字符变量,我想将其更改为 Date 类的变量,并使用 days_in_month() 将其更改为该月的最后一天。

我的字符变量目前采用 Year-Mo 形式,例如2017 年 1 月,2017 年 2 月。

我将如何使用 as.Date 和 days_in_month 来做到这一点

【问题讨论】:

    标签: r lubridate


    【解决方案1】:

    这是一个很好的问题,因为它被问过很多次了! 看看这些答案:

    R calculate month end

    Create end of the month date from a date variable

    伟大的部分?软件包一直在更新,因此有时答案不再有效。这里不是这样。

    @Edgar Santos 在第一个链接中给出了完全符合您的问题的详细答案。

    library(lubridate)
    
    dt <- c("2017-01","2017-02")  # data
    dt <- ym(dt)                  # change to date of year-month format
    day(dt) <- days_in_month(dt)  # update the 'day' in the date
    
    [1] "2017-01-31" "2017-02-28"
    

    【讨论】:

    • 当我尝试编织到 pdf 时收到一条错误消息,说“找不到函数“days_in_month””你知道为什么会出现这个错误消息
    • 你很久以前就问过这个问题了,很抱歉!该功能在包lubridate 中。如果您收到该错误,则说明您没有安装该软件包、未调用该库,或两者兼而有之。
    【解决方案2】:
    vec <- c("2017-01", "2017-02")
    dates <- as.POSIXlt(as.Date(paste(vec, "01"), format = "%Y-%m %d"))
    dates$mon <- dates$mon + 1
    dates$mday <- dates$mday - 1
    as.Date(dates)
    # [1] "2017-01-31" "2017-02-28"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-06
      • 2018-07-31
      • 1970-01-01
      相关资源
      最近更新 更多