添加一个月到一个日期 [英] Add a month to a Date

查看:134
本文介绍了添加一个月到一个日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试添加一个月的日期。但是到目前为止,它不可能以直线的方式。以下是我试过的。

  d<  -  as.Date(2004-01-31)
d + 60
#[1]2004-03-31

添加不帮助这个月不会重叠。

  seq(as.Date(2004-01-31),by =month ,length = 2)
#[1]2004-01-312004-03-02

以上可能会起作用,但再次不直接。
此外,它还添加了30天或某些日期,有以下问题的日期

  seq(as.Date (2004-01-31),by =month,length = 10)
#[1]2004-01-312004-03-022004-03-31 2004-05-012004-05-312004-07-012004-07-312004-08-312004-10-012004-10-31

在上述中,前2个日期,月份未更改。



此外,以下方法也失败了一个月,但是成功了一年。

  d<  -  as .POSIXlt(as.Date(2010-01-01))
d $ year< - d $ year +1
d
#[1]2011-01-01 UTC
d< - as.POSIXlt(as.Date(2010-01-01))
d $ month< - d $ month +1
d




format.POSIXlt(x,usetz = TRUE)中的错误:invalid'x'argument


正确的方法是什么?

解决方案

香草R有一个天真的愚蠢课,但是 Lubridate CRAN 包可以让你做你所要求的:

  require(lubridate)
d< - as.Date('2004-01-01')
月(d)< - 月(d)+ 1
day(d)< - days_in_month(d)
d
[1]2004-02-29
/ pre>

希望有所帮助。


I am trying to add a month to a date i have. But then its not possible in a straight manner so far. Following is what i tried.

d <- as.Date("2004-01-31")
d + 60
# [1] "2004-03-31"

Adding wont help as the month wont be overlapped.

seq(as.Date("2004-01-31"), by = "month", length = 2) 
# [1] "2004-01-31" "2004-03-02"

Above might work , but again its not straight forward. Also its also adding 30 days or something to the date which has issues like the below

seq(as.Date("2004-01-31"), by = "month", length = 10) 
#  [1] "2004-01-31" "2004-03-02" "2004-03-31" "2004-05-01" "2004-05-31" "2004-07-01" "2004-07-31" "2004-08-31" "2004-10-01" "2004-10-31"

In the above , for the first 2 dates , month haven’t changed.

Also the following approach also failed for month but was success for year

d <- as.POSIXlt(as.Date("2010-01-01"))
d$year <- d$year +1
d
# [1] "2011-01-01 UTC"
d <- as.POSIXlt(as.Date("2010-01-01"))
d$month <- d$month +1
d

Error in format.POSIXlt(x, usetz = TRUE) : invalid 'x' argument

What is the right method to do this ?

解决方案

Vanilla R has a naive difftime class, but the Lubridate CRAN package lets you do what you ask:

require(lubridate)
d <- as.Date('2004-01-01')
month(d) <- month(d) + 1
day(d) <- days_in_month(d)
d
[1] "2004-02-29"

Hope that helps.

这篇关于添加一个月到一个日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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