Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

First day of the month from a POSIXct date time using lubridate

Tags:

r

lubridate

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")
like image 291
nacnudus Avatar asked May 12 '14 06:05

nacnudus


People also ask

Which Lubridate function will produce the first day of the next month?

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().

How do you find the day of the week from a date Lubridate?

wday() returns the day of the week as a decimal number or an ordered factor if label is TRUE .

What does Lubridate mean?

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.


2 Answers

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"
like image 98
Frank Avatar answered Nov 04 '22 14:11

Frank


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"
like image 24
Roland Avatar answered Nov 04 '22 14:11

Roland