Add a month to a Date [duplicate]

2019-01-04 09:39发布

This question already has an answer here:

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 ?

8条回答
手持菜刀,她持情操
2楼-- · 2019-01-04 10:09

"mondate" is somewhat similar to "Date" except that adding n adds n months rather than n days:

> library(mondate)
> d <- as.Date("2004-01-31")
> as.mondate(d) + 1
mondate: timeunits="months"
[1] 2004-02-29
查看更多
Bombasti
3楼-- · 2019-01-04 10:15

The simplest way is to convert Date to POSIXlt format. Then perform the arithmetic operation as follows:

date_1m_fwd     <- as.POSIXlt("2010-01-01")
date_1m_fwd$mon <- date_1m_fwd$mon +1

Moreover, incase you want to deal with Date columns in data.table, unfortunately, POSIXlt format is not supported.

Still you can perform the add month using basic R codes as follows:

library(data.table)  
dt <- as.data.table(seq(as.Date("2010-01-01"), length.out=5, by="month"))  
dt[,shifted_month:=tail(seq(V1[1], length.out=length(V1)+3, by="month"),length(V1))]

Hope it helps.

查看更多
Viruses.
4楼-- · 2019-01-04 10:15

I turned antonio's thoughts into a specific function:

library(DescTools)

> AddMonths(as.Date('2004-01-01'), 1)
[1] "2004-02-01"

> AddMonths(as.Date('2004-01-31'), 1)
[1] "2004-02-29"

> AddMonths(as.Date('2004-03-30'), -1)
[1] "2004-02-29"
查看更多
等我变得足够好
5楼-- · 2019-01-04 10:20

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.

查看更多
够拽才男人
6楼-- · 2019-01-04 10:20
addedMonth <- seq(as.Date('2004-01-01'), length=2, by='1 month')[2]
addedQuarter <- seq(as.Date('2004-01-01'), length=2, by='1 quarter')[2]
查看更多
甜甜的少女心
7楼-- · 2019-01-04 10:28

Function %m+% from lubridate adds one month without exceeding last day of the new month.

library(lubridate)
(d <- ymd("2012-01-31"))
 1 parsed with %Y-%m-%d
[1] "2012-01-31 UTC"
d %m+% months(1)
[1] "2012-02-29 UTC"
查看更多
登录 后发表回答