tlev tlev - 1 year ago 79
R Question

Add a Year to a Month and Day in R

I have a dataset where some of the entries in the date column do not have years and I need to add the year 2016:

  • So some of the entries will say something like this: "Apr 11"

  • Other entries will say something like this: "11 Apr 2015"

For those entries that don't contain a year (of which there are many and which span a variety of different dates), I would like to add the year 2016.

How do I do this?

Answer Source

We can use sub to paste 2016 for elements that contain only month and day. Match one or more space (\\s+) followed by two digits (\\d{2}) that we capture as a group ((...)) at the end ($) of the string and replace it with space followed by the backreference of the capture group (\\1) followed by space and 2016.

sub("\\s+(\\d{2})$", " \\1 2016", str1)
#[1] "Apr 11 2016" "Apr 11 2015"

Based on the update in the OP's post, we can also use lubridate to convert to 'Date'

as.Date(parse_date_time(str2, c('md', 'dmy')))
#[1] "2016-04-11" "2015-04-11"


str1 <- c("Apr 11", "Apr 11 2015")
str2 <- c("Apr 11", "11 Apr 2015")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download