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