R中一系列日期中最后一次观察月份的顺序

时间:2018-07-30 19:17:08

标签: r

如果我的工作日日期范围从2010-01-042014-12-31,如何创建包含向量中每个月的最后日期的日期向量?

我已经浏览了动物园和润滑包装,但找不到任何相关的东西。

2 个答案:

答案 0 :(得分:2)

这是完成工作的两个步骤:

  1. 使用lubridate::ceiling_date来获取下个月的第一天
  2. 我们生成一个“按月”序列并减去1天

# generage some random dates
set.seed(123)
mydates <- sample(seq(from = as.Date("2017-01-01"), 
                      to   = as.Date("2018-12-31"), by="day"), 10)

# generate requested sequence
d1 <- lubridate::ceiling_date(min(mydates), "month")
d2 <- lubridate::ceiling_date(max(mydates), "month")

result <- seq(from=d1, to=d2, by="month") - 1

答案 1 :(得分:1)

尚不清楚您是要两个日期的所有月末加上它们之间的所有月份,还是只想两个日期,但是在下面显示了两者。

1)这是使用yearmon类的单行代码,给出了从第一个日期到第二个日期的所有月末。将每个输入字符串转换为yearmon类,创建它们的序列,然后使用等于1(表示每月的最后一天)的Date转换为frac类。

library(zoo)
as.Date(seq(as.yearmon("2010-01-04"), as.yearmon("2014-12-31"), 1/12), frac = 1)

给予:

[1] "2010-01-31" "2010-02-28" "2010-03-31" "2010-04-30" "2010-05-31"
[6] "2010-06-30" "2010-07-31" "2010-08-31" "2010-09-30" "2010-10-31"
[11] "2010-11-30" "2010-12-31" "2011-01-31" "2011-02-28" "2011-03-31"
[16] "2011-04-30" "2011-05-31" "2011-06-30" "2011-07-31" "2011-08-31"
[21] "2011-09-30" "2011-10-31" "2011-11-30" "2011-12-31" "2012-01-31"
[26] "2012-02-29" "2012-03-31" "2012-04-30" "2012-05-31" "2012-06-30"
[31] "2012-07-31" "2012-08-31" "2012-09-30" "2012-10-31" "2012-11-30"
[36] "2012-12-31" "2013-01-31" "2013-02-28" "2013-03-31" "2013-04-30"
[41] "2013-05-31" "2013-06-30" "2013-07-31" "2013-08-31" "2013-09-30"
[46] "2013-10-31" "2013-11-30" "2013-12-31" "2014-01-31" "2014-02-28"
[51] "2014-03-31" "2014-04-30" "2014-05-31" "2014-06-30" "2014-07-31"
[56] "2014-08-31" "2014-09-30" "2014-10-31" "2014-11-30" "2014-12-31"

2),或者如果您只是想为每个输入日期指定对应的月末,则可以使用以下格式:

library(zoo)

x <- c("2010-01-04", "2014-12-31") # input data
as.Date(as.yearmon(x), frac = 1)

给予:

[1] "2010-01-31" "2014-12-31"

2a)要在没有任何软件包的情况下执行此操作,请先定义“月初”功能,然后将其应用两次,如图所示。

fom <- function(x) as.Date(cut(as.Date(x), "month"))
fom(fom(x) + 31) - 1

给予:

[1] "2010-01-31" "2014-12-31"