0
YR = "2021"

Then my result should:

levels = c("202101", "202102", "202103", "202104", "202105", "202106", "202107", "202108", "202109", "202110", "202111", "202112"),

labels = c("Jan-2021", "Feb-2021", "Mar-2021", "Apr-2021","May-2021","Jun-2021","Jul-2021","Aug-2021","Sep-2021","Oct-2021","Nov-2021","Dec-2021"))

This is created for labels.

If I change it to

YR = 2022 

Then my result should:

levels: c("202201","202202",...,"202212"), 
labels = c("Jan-2022", "Feb-2022",...,"Dec-2022"))
markus
  • 25,843
  • 5
  • 39
  • 58
  • 2
    A bit of a tweak to previous answers like https://stackoverflow.com/questions/5812493/how-to-add-leading-zeros or https://stackoverflow.com/questions/40658189/create-sequence-of-numbers-with-leading-zeroes should do it. E.g.: `sprintf('%d%02d', 2021, 1:12)` – thelatemail Apr 28 '21 at 21:12
  • 1
    I don't understand your intended result. Is that a `data.frame` with 2 columns? – thelatemail Apr 28 '21 at 21:40

1 Answers1

2
  1. the first target can refer the link in the comment.
  2. month.abb function can provide the abbreviation of each month.
YR = "2021"
levels <- sprintf('%s%02d', YR, 1:12)
levels
#>  [1] "202101" "202102" "202103" "202104" "202105" "202106" "202107" "202108"
#>  [9] "202109" "202110" "202111" "202112"
labels <- paste0(month.abb,"-",YR)
# or
# labels <- sprintf('%s%s%s',month.abb,"-",YR)
labels
#>  [1] "Jan-2021" "Feb-2021" "Mar-2021" "Apr-2021" "May-2021" "Jun-2021"
#>  [7] "Jul-2021" "Aug-2021" "Sep-2021" "Oct-2021" "Nov-2021" "Dec-2021"

Created on 2021-04-29 by the reprex package (v2.0.0)

Peace Wang
  • 2,399
  • 1
  • 8
  • 15
  • While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – Gerhard Apr 29 '21 at 06:34
  • Thanks for your notification. But sometimes code itself with necessary comment is enough for some specific question. Not each simple code needed to be explained. If I think it's hard to understand, I will explain it without hesitation. – Peace Wang Apr 29 '21 at 06:55