EDC
EDC

Reputation: 633

How to lag dates in form of strings in R

The following vector of Dates is given in form of a string sequence:

d <- c("01/09/1991","01/10/1991","01/11/1991","01/12/1991")  

I would like to exemplary lag this vector by 1 month, that means to produce the following structure:

d <- c("01/08/1991","01/09/1991","01/10/1991","01/11/1991")

My data is much larger and I must impose higher lags as well, but this seems to be the basis I need to know. By doing this, I would like to have the same format in the end again:("%d/%m/%Y). How can this be done in R? I found a couple of packages (e.g. lubridate), but I always have to convert between formats (strings, dates and more) so it's a bit messy and seems prone to mistake.
edit: some more info on why I want to do this: I am using this vector as rownames of a matrix, so I would prefer a solution where the final outcome is a string vector again.

Upvotes: 0

Views: 828

Answers (2)

G. Grothendieck
G. Grothendieck

Reputation: 269556

This does not use any packages. We convert to "POSIXlt" class, subtract one from the month component and convert back:

fmt <- "%d/%m/%Y"
lt <- as.POSIXlt(d, format = fmt)
lt$mon <- lt$mon - 1
format(lt, format = fmt)
## [1] "01/08/1991" "01/09/1991" "01/10/1991" "01/11/1991"

Upvotes: 3

etienne
etienne

Reputation: 3678

My solution uses lubridatebut it does return what you want in the specified format:

require(lubridate)
d <- c("01/09/1991","01/10/1991","01/11/1991","01/12/1991")  
format(as.Date(d,format="%d/%m/%Y")-months(1),'%d/%m/%Y')

[1] "01/08/1991" "01/09/1991" "01/10/1991" "01/11/1991"

You can then change the lag and (if you want) the output (which is this part : '%d/%m/%Y') by specifying what you want.

Upvotes: 2

Related Questions