给定一个 POSIXct 日期时间,如何提取该月的第一天进行聚合?
library(lubridate)
full.date <- ymd_hms("2013-01-01 00:00:21")
lubridate有一个函数称为floor_date
向下舍入日期时间。调用它unit = "month"
正是你想要的:
library(lubridate)
full.date <- ymd_hms("2013-01-01 00:00:21")
floor_date(full.date, "month")
[1] "2013-01-01 UTC"
我看不出使用 lubridate 的理由:
full.date <- as.POSIXct("2013-01-11 00:00:21", tz="GMT")
monthStart <- function(x) {
x <- as.POSIXlt(x)
x$mday <- 1
as.Date(x)
}
monthStart(full.date)
#[1] "2013-01-01"
first.of.month <- ymd(format(full.date, "%Y-%m-01"))
first.of.month
[1] "2013-01-01 UTC"
我有另一个解决方案:
first.of.month <- full.date - mday(full.date) + 1
但它需要库'lubridate'或'date.table'(与data.table聚合)