在R中生成一个月的最后一天的日期序列 [英] generate a date sequence of last day of month in R

查看:44
本文介绍了在R中生成一个月的最后一天的日期序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我给出开始日期和结束日期以及频率,我应该能够生成从开始到结束的一系列日期,这样

If I give a start date and end date, and a frequency I should be able to generate a sequence of dates from start to end such that

1)日期是该月的最后一天.2)我可以将序列的频率设置为12的任意因子(12个月).假设频率为3,则表示间隔或间隔为4个月.

1) the dates are the last day of the month. 2) I can set the frequency of sequence to any factor of 12 (wrt 12 months). Say if the frequency is 3, it means there is an interval or gap of 4 months.

对于(1),以下函数为我提供了间隔为3个月(即每季度一次)的输出,但没有给出日期与该月的最后一天的距离.

For (1) the following function gives me an output with an interval of 3 months (ie quarterly)but it doesn't give the dates with last day of the month.

    DateSeq<-function(st,en, freq){
    seq(st, en, by = paste(as.character(12/freq), "months"))
    }
    DateSeq(as.Date("2015-01-01"),as.Date("2018-03-03"),4)

如何将其转换为给我最后一天的序列?给我一个简单的代码.

how to convert this to a sequence that gives me last day.? Give me a simple code.

推荐答案

这给出了月末日期的顺序,从 st 的年/月到的年/月.> en .

This gives a sequence of end-of-month dates from the year/month of st to the year/month of en.

library(zoo)
as.Date(seq(as.yearmon(st), as.yearmon(en), by = 1 / freq), frac = 1)

在上面的 st en 中,可以是任何可转换为 yearmon 的类,包括 yearmon 本身, Date ,字符串或数字.例如,"2000-02-01" "2000-02" as.Date("2000-02-01") 2000 + 1/12 .

In the above st and en could be any class that converts to yearmon including yearmon itself, Date, character strings or numeric. For example, "2000-02-01", "2000-02", as.Date("2000-02-01"), 2000+1/12.

如果 en 是日期,并且序列的结束日期应不晚于 en ,则将 as.yearmon(en)替换为如果 en 不在月底,则使用以下代码减去1/12.

If en is a date and the end date of the sequence should be no later than en then replace as.yearmon(en) with the following which subtracts 1/12 if en is not at the end of the month.

as.yearmon(en) - (as.Date(en) < as.Date(as.yearmon(en), frac = 1)) / 12

类似地,如果 st 是一个日期,并且序列的开始日期应不晚于 st ,则使用相同的思想减去 st 不在该月底用

替换 as.yearmon(st)

Similarly if st is a date and the starting date of the sequence should be no later than st use the same idea to subtract 1/12 if st is not at the end of the month replacing as.yearmon(st) with

as.yearmon(st) - (as.Date(st) < as.Date(as.yearmon(st), frac = 1)) / 12

我们是否真的需要日期,这是一个疑问,因为它们总是在月底.似乎关键是要创建一个年/月序列,而月末日期只是表示该序列的一种方式.一种更简单的方法是直接将此 yearmon 序列.

There is some question regarding whether we really need dates at all since they are always at the end of the month. It seems that the point is to create a year/month sequence and the end-of-month dates are just a way to represent that. A simpler way would be this yearmon sequence directly.

seq(as.yearmon(st), as.yearmon(en), by = 1 / freq)

这篇关于在R中生成一个月的最后一天的日期序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆