通过日期变量创建月末日期 [英] Create end of the month date from a date variable

查看:86
本文介绍了通过日期变量创建月末日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有日期变量的大数据框,它反映了每月的第一天。有没有简单的方法来创建表示月份的最后一天的新数据框日期变量?

I have a large data frame with date variables, which reflect first day of the month. Is there an easy way to create a new data frame date variable that represents the last day of the month?

下面是一些示例数据:

date.start.month=seq(as.Date("2012-01-01"),length=4,by="months")
df=data.frame(date.start.month)
df$date.start.month

"2012-01-01" "2012-02-01" "2012-03-01" "2012-04-01"

我想返回一个新变量,其内容如下:

I would like to return a new variable with:

"2012-01-31" "2012-02-29" "2012-03-31" "2012-04-30"

我尝试了以下操作,但未成功:

I've tried the following but it was unsuccessful:

df$date.end.month=seq(df$date.start.month,length=1,by="+1 months")


推荐答案

要获得月底的收入,您可以创建一个 Date 向量,其中包含随后所有月份的第一天,并减去1天。

To get the end of months you could just create a Date vector containing the 1st of all the subsequent months and subtract 1 day.

date.end.month <- seq(as.Date("2012-02-01"),length=4,by="months")-1
date.end.month
[1] "2012-01-31" "2012-02-29" "2012-03-31" "2012-04-30"

这篇关于通过日期变量创建月末日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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