Format year half contained in text as dates

Viewed 507

I have date values contained in text, each containing a half of the year:

date_by_half <- c("2016 H1", "2017 H2", "2018 H1")

I'd like to extract the date from text and store as the first day of each half or "semester". So, something like:

ysemester(date_by_half)
#[1] "2016-01-01" "2017-07-01" "2018-01-01"

I'm familiar with lubridate::yq() function, but I found that this only works for quarters.

lubridate::yq(date_by_half)
#[1] "2016-01-01" "2017-04-01" "2018-01-01"

Right now my work around is to replace H2 with Q3:

lubridate::yq(stringr::str_replace(date_by_half,"H2", "Q3"))
#[1] "2016-01-01" "2017-07-01" "2018-01-01"

However, I'm wondering if there is a more eloquent solution using lubridate (or some other quick and reusable method).

3 Answers

One liners

These one-liners use only base R:

1) read.table/ISOdate

with(read.table(text = date_by_half), as.Date(ISOdate(V1, ifelse(V2=="H1",1,7), 1)))
## [1] "2016-01-01" "2017-07-01" "2018-01-01"

2) sub Even shorter is:

as.Date(sub(" H2", "-7-1", sub(" H1", "-1-1", date_by_half)))
## [1] "2016-01-01" "2017-07-01" "2018-01-01"

S3

Another approach would be to create an S3 class, "half", for half year dates. We will only implement the methods we need.

as.half <- function(x, ...) UseMethod("as.half")

as.half.character <- function(x, ...) {
  year <- as.numeric(sub("\\D.*", "", x))
  half <- as.numeric(sub(".*\\D", "", x))
  structure(year + (half - 1)/2, class = "half")
}

as.Date.half <- function(x, ...) {
  as.Date(ISOdate(as.integer(x), 12 * (x - as.integer(x)) + 1, 1))
}

# test

as.Date(as.half(date_by_half))
## [1] "2016-01-01" "2017-07-01" "2018-01-01"

You can make your own function to do the trick.

# Your data
date_by_half <- c("2016 H1", "2017 H2", "2018 H1")

# Function to do the work
year_dater <- function(dates) {
  year <- substr(dates, 1, 4)
  quarter <- substr(dates, 6, 7)
  month <- ifelse(quarter=="H1", 1, 7) 
  dates <- paste0(year, "-", month, "-", rep(1, length(month)))

  return(dates)
}

# Running the function
dates <- year_dater(date_by_half)

# As date format
as.POSIXct(dates)
"2016-01-01 CET"  "2017-07-01 CEST" "2018-01-01 CET" 

We can use ceiling_date function from lubridate with unit as "halfyear" and change_on_boundary parameter set to FALSE so that the dates on boundary (2018-01-01, 2017-07-01 etc.) are never rounded up along with yq function.

library(lubridate)
ceiling_date(yq(date_by_half), unit = "halfyear", change_on_boundary = FALSE)
#[1] "2016-01-01" "2017-07-01" "2018-01-01"
Related