使用 days_in_month 将日期更改为该月的最后一天

Change date to the last day of month using days_in_month

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

我的字符变量目前的格式是 Year-Mo,例如2017-01, 2017-02.

我如何使用 as.Date 和 days_in_month

来做到这一点
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"

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

Create end of the month date from a date variable

最重要的部分?软件包一直在更新,所以有时答案不再有效。这里不是这种情况。

@Edgar Santos,在第一个 link 给出了一个非常适合你的问题的详细答案。

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"