Given a POSIXct date time, how do you extract the first day of the month for aggregation?
library(lubridate)
full.date <- ymd_hms("2013-01-01 00:00:21")
Lubridate has two really cool functions to get the first day or the last day of a particular month. These functions are floor_date() and ceiling_date().
wday() returns the day of the week as a decimal number or an ordered factor if label is TRUE .
Lubridate is an R package that makes it easier to work with dates and times. Below is a concise tour of some of the things lubridate can do for you. Lubridate was created by Garrett Grolemund and Hadley Wickham, and is now maintained by Vitalie Spinu.
lubridate has a function called floor_date
which rounds date-times down. Calling it with unit = "month"
does exactly what you want:
library(lubridate)
full.date <- ymd_hms("2013-01-01 00:00:21")
floor_date(full.date, "month")
[1] "2013-01-01 UTC"
I don't see a reason to use 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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With