Search code examples
rfunctionsapply

Write a vector of year-month with a loop or function in R


I want to make a vector of year-month between 2018 and 2020 without typing one by one, such as 2018-01, 2018-02 ... 2020-01.

This is the expected outcome

month_names <- c("2018-01", "2018-02", "2018-03", ..... "2020-01")

Any help will be appreciated.


Solution

  • You could create a monthly sequence using seq and use format.

    month_names <- format(seq(as.Date("2018-04-01"), as.Date("2020-04-01"), 
                           by = 'month'), '%Y-%m')
    
     #[1] "2018-04" "2018-05" "2018-06" "2018-07" "2018-08" "2018-09" "2018-10"
     #[8] "2018-11" "2018-12" "2019-01" "2019-02" "2019-03" "2019-04" "2019-05"
    #[15] "2019-06" "2019-07" "2019-08" "2019-09" "2019-10" "2019-11" "2019-12"
    #[22] "2020-01" "2020-02" "2020-03" "2020-04"
    

    Another way with outer :

    c(t(outer(2018:2020, sprintf("%02d", 1:12), paste, sep = "-")))