R function: vector of dates

Here I present a simple R function that may be useful for time series analyses. The function outputs a character vector of length defined in total_days, each element representing a date, starting from the day, month and year chosen by the user, with a particular format also defined by the user. This function may be useful to get the labels of the x axis for plots.

Input numeric values for day, month, year and total_days. Customize the format of the date: choose between “d”, “m”, “y”, “dm”, “mdy” or “dmy” (“d”: day; “m”: month; “y”: year). Choose the character string that will separate the terms (only valid when format is “dm”, “mdy” or “dmy”).

date_vec <- function(day = 1, month = 1, year = 2020, 
                     total_days = 40, format = "dmy", sep = "/")
{
  ...
}

For example, let’s generate a vector of 5 dates from the December 30 of 2020:

> date_vec(day = 30, month = 12, year = 2020, total_days = 5)

1] "30/12/2020" "31/12/2020" "01/01/2021" "02/01/2021" "03/01/2021"

Let’s change the format:

> date_vec(day = 30, month = 12, year = 2020, total_days = 5, format = "mdy", sep = "-")

[1] "12-30-2020" "12-31-2020" "01-01-2021" "01-02-2021" "01-03-2021"

The function supports leap years (i.e. 29 days for February in leap years):

> date_vec(day = 26, month = 2, year = 2016, total_days = 5)

[1] "26/02/2016" "27/02/2016" "28/02/2016" "29/02/2016" "01/03/2016"

You can get the full code for this function from my GitHub page, here.