jw123456
jw123456

Reputation: 33

R: Correcting the year of a date in R

I have a dataframe with observations and the dates at which they were made. The dates are read from a csv file, but only include month and day. R assumes that they are all from 2016. I know that the dates are in order from most to least recent, so how would I go about adding on the correct years?

The inputs are in order from most to least recent.

Input            Output
1/1              1/1/2016
12/1             12/1/2015
11/1             11/1/2015
1/1              1/1/2015
12/1             12/1/2014
1/1              1/1/2014
12/1             12/1/2013

Thanks for your time!

Upvotes: 3

Views: 163

Answers (1)

akrun
akrun

Reputation: 886938

If the data is ordered as showed in the OP's post, we can extract the month part from the initial vector ('v1') using sub, convert to numeric, get the difference of adjacent elements, check whether it is greater than 0, cumsum the logical vector, use that grouping index to pass the year values, finally paste it with the initial vector.

v2 <- paste(v1, c(2016:2013)[cumsum(c(TRUE,
          diff(as.numeric(sub("/.*", "", v1))) > 0))], sep="/")

If we need to convert to 'Date' class, use as.Date with the correct format.

as.Date(v2, "%m/%d/%Y")
#[1] "2016-01-01" "2015-12-01" "2015-11-01" "2015-01-01" "2014-12-01"
#[6] "2014-01-01" "2013-12-01"

Upvotes: 2

Related Questions