在R中获取上一年的最后一天?
所以问题是如何选择上一年的最后一天。我想把它设置成自动的,因为我们可能会做几年 我已经设置了以下内容:在R中获取上一年的最后一天?,r,R,所以问题是如何选择上一年的最后一天。我想把它设置成自动的,因为我们可能会做几年 我已经设置了以下内容: lastyear <- as.numeric(format(today, "%Y")) - 1 去年类似这样的事情可能: last_day <- function(x) { lastyear <- as.numeric(format(x, "%Y")) - 1 last_date <- as.Date(sprintf('%s-12-31',lastyear))
lastyear <- as.numeric(format(today, "%Y")) - 1
去年类似这样的事情可能:
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"
last_day这里有一个哈德利诗歌版本:
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"
库(lubridate)
上一年的最后一天,你肯定这将是自动化的?从我看来,它是,但我是一个R Noob:)我已经试过几次了,只要你给它输入一个日期:)@NealC可能最好改变这个被接受的答案。虽然我很确定我的函数可以正常工作(只要输入是日期),但从软件包中使用类似floor\u Date
的函数是一个更好的解决方案,因为它在大多数情况下都经过了错误测试。是的,可能必须使用这个函数。两行代码要好得多。抱歉@LyzandeR:PYou最近做得对。我也提出了同样的建议。这与行数无关,而是因为包中的函数已经过bug测试。啊,好吧。整合脚本对我来说非常重要,尽管使用某些包和避免使用其他包很重要,但使用更少的代码仍然很好@LyzandeR但谢谢你们两个@NealC另一个解决方案只有两行,因为它是这样写的。您可以轻松地组合成一个包,而不必依赖于另一个包<代码>as.Date(sprintf('%s-12-31',as.numeric(format(x,“%Y”))-1)
或as.Date(paste0(as.numeric(format(Sys.Date(),“%Y”)-1,“-12-31”))
库(lubridate);as.Date(paste0(year(Sys.Date())-1,“-12-31”)
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")