在R中获得前一年的最后一天?

时间:2015-01-08 16:50:50

标签: r

所以问题是如何选择上一年的最后一天。我想把它设置为自动,因为我们可能会这样做几年。

我已经建立的是:

lastyear <- as.numeric(format(today, "%Y")) - 1

今天只是一个带有Sys.Date()的对象,所以我不相信我需要为此提供代码? (如果有人真的想知道,那就是约会的格式。)

我上面的代码让前一年变得很好,但是我想要一些可以选择的东西&#34; 2014-12-31&#34;为了我。

所以,重复的问题是我如何 自动 挑选出去年的最后一天?

另外,我在这个脚本中使用了lubridate。

2 个答案:

答案 0 :(得分:7)

这是一个Hadleyverse版本:

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"

我实际上已经投了“基数”答案,因为它是 base 并且 - 正如GSee指出的那样 - 不太可能有问题。 lubridate回答最重要的是可读性。它也会失去速度:

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

enter image description here

答案 1 :(得分:5)

这样的事情可能是:

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"