Reputation: 1090
So the question is how to select the last day of the previous year. I want to set this up to be automatic, cause we might do it for a couple of years.
What I have set up already is this :
lastyear <- as.numeric(format(today, "%Y")) - 1
Today is just an object with Sys.Date() in it so I don't believe I need to provide code for that? (It's in the format of a date if anyone really wants to know.)
The code I have above gets the previous year fine, but I want something that picks out "2014-12-31" for me.
So, the question repeated would be how can I automatically pick out the last day of the previous year?
Also, I use lubridate in this script.
Upvotes: 5
Views: 5650
Reputation: 78792
Here's a Hadleyverse version:
library(lubridate)
last_day_prev_year <- function(x) floor_date(x, "year") - days(1)
last_day_prev_year(Sys.Date())
## [1] "2014-12-31 UTC"
I actually up-voted the "base" answer since, well, it's base and—as GSee pointed out—less likely to be problematic. The biggest thing the lubridate answer has going for it is readability. It loses on speed, too:
library(microbenchmark)
library(lubridate)
ldpy_base <- function(x) {
lastyear <- as.numeric(format(x, "%Y")) - 1
last_date <- as.Date(sprintf('%s-12-31',lastyear))
}
ldpy_lubridate <- function(x) floor_date(x, "year") - days(1)
mb <- microbenchmark(ldpy_base(Sys.Date()),
ldpy_lubridate(Sys.Date()),
times=5000)
autoplot(mb) + labs(title="5,000 runs, base vs lubridate")
Upvotes: 12
Reputation: 37879
Something like this maybe:
last_day <- function(x) {
lastyear <- as.numeric(format(x, "%Y")) - 1
last_date <- as.Date(sprintf('%s-12-31',lastyear))
}
> a<-last_day(Sys.Date())
> a
[1] "2014-12-31"
> class(a)
[1] "Date"
Upvotes: 9