I want to generate month names before a specified month. In the example below, I am trying to generate 8 months before Oct. Output is Mar through Oct.
headers <- "Oct"
length <- 8
end <- which(month.abb %in% headers)
months <- month.abb[(end-length 1):end]
It does not work if I enter 12 in length. In that case I want output - Nov through Oct.
CodePudding user response:
Maybe this?
headers <- "Oct"
length <- 12
idx <- match(headers, month.abb)
month.abb2 <- rep(month.abb,2)
month.abb2[(idx-length 1):idx 12]
CodePudding user response:
The trick is to use the modulo operator, therefore negative values are truncated to the range 1..12. You can even use an arbitrary length > 12, such as length = 100, if you want.
headers <- "Oct"
length <- 12
end <- which(month.abb %in% headers)
months <- month.abb[(((end-length 1):end) - 1) %% 12 1]
Explanation:
- You first have a range, such as -1:10.
- You subtract 1 from the range, because our indexes to month.abb start at 1 but the modulo operator always returns values starting from zero. Now you have a range -2:11.
- You apply the modulo 12. Now you have: 10 11 0 1 2 3 4 5 6 7 8 9.
- You add 1 again that you had previously subtracted, because array indexes start at 1. Now you have: 11 12 1 2 3 4 5 6 7 8 9 10.
- These indexes are used to access elements of month.abb.