Skip to content

Instantly share code, notes, and snippets.

@jeremy-allen
Created May 12, 2020 15:47
Show Gist options
  • Save jeremy-allen/cd684a87de38538ad3cb9f853fe09bb7 to your computer and use it in GitHub Desktop.
Save jeremy-allen/cd684a87de38538ad3cb9f853fe09bb7 to your computer and use it in GitHub Desktop.
return a character vector of the last 12 months, ending with current month
order_months <- function(x = NULL, label = "abb") {
# This function takes a given month number or the current month
# number and returns a character vector of the last 12 months,
# including current month. For example, if it is now February:
# "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec" "Jan" "Feb"
# is returned with the current month at the end.
# This makes a nice x axis if you need to plot something for
# the "last 12 months".
# if x is NULL the current month is taken from Sys.Date
# if x is given, x must be 1-12
# if label is "abb", month names are abbreviated
# if label is "names", month names are full
# stop if x is out of bounds
if(!is.null(x))
if(x > 12 | x < 1) stop("x must be 1-12")
# sets of named integers using abbreviated and full month names
months_abb <- setNames(1:12, month.abb)
months_names <- setNames(1:12, month.name)
# current month number
m <- as.POSIXlt(Sys.Date())$mon + 1
# get a value for x
if(is.null(x)) x <- m + 1 else x <- x + 1
# a and b components for main if
# if x is 1 or 12
a <- 1:12
# if x is 2 through 12
b <- c(
x:12,
1:(x-1)
)
# main if
if(x == 1 | x == 13) new_order <- a else new_order <- b
# use new_order to set desired order of months
if(label == "abb") my_month_order <- names(months_abb[new_order])
if(label == "names") my_month_order <- names(months_names[new_order])
my_month_order
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment