28

给定一个 POSIXct 日期时间,如何提取该月的第一天进行聚合?

library(lubridate)

full.date <- ymd_hms("2013-01-01 00:00:21")
4

4 回答 4

68

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"
于 2015-11-12T01:01:58.380 回答
28

我看不出使用 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"
于 2014-05-12T07:15:16.860 回答
14
first.of.month <- ymd(format(full.date, "%Y-%m-01"))
first.of.month

[1] "2013-01-01 UTC"
于 2014-05-12T06:51:56.310 回答
2

我有另一个解决方案:

first.of.month <- full.date - mday(full.date) + 1

但它需要库'lubridate'或'date.table'(与data.table聚合)

于 2016-10-26T13:42:02.120 回答