从[r]数据框中的date变量创建月末日期的方法
问题描述:
我有一个具有日期变量的[r]大数据框,这反映了月的第一天。这是一个简单的方法来克服代表本月最后一天的新的数据框架日期变量?
I have a [r] large data frame with date variables, which reflect first day of the month. Is the a easy way to crete 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"
我想返回一个新的变量wtih:
I would like to return a new variable wtih:
"2012-01-31" "2012-02-29" "2012-03-30" "2012-04-27"
我已经尝试过,但不成功:
I've tried the follwing but it was unsucessful:
df$date.end.month=seq(df$date.start.month,length=1,by="+1 months")
对这个新的[r]用户的任何指导都将不胜感激。
Any guidance to this new [r] user would be greatly appreciated.
答
要获得月底,您可以创建一个 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"