Home > other >  String sequence starting with a running character and then with a vector of numbers
String sequence starting with a running character and then with a vector of numbers

Time:10-21

I want to have the following string sequence as result:

"2016-01" "2016-02" "2016-03" "2016-04" "2016-05" "2016-06" "2016-07" "2016-08" "2016-09" "2016-10" "2016-11" "2016-12" "2017-01" "2017-02" "2017-03" "2017-04" "2017-05" "2017-06" "2017-07" "2017-08" "2017-09" "2017-10" "2017-11" "2017-12" "2018-01" "2018-02" "2018-03" "2018-04" "2018-05" "2018-06" "2018-07" "2018-08" "2018-09" "2018-10" "2018-11" "2018-12" "2019-01" "2019-02" "2019-03" "2019-04" "2019-05" "2019-06" "2019-07" "2019-08" "2019-09" "2019-10" "2019-11" "2019-12" "2020-01" "2020-02" "2020-03" "2020-04" "2020-05" "2020-06" "2020-07" "2020-08" "2020-09" "2020-10" "2020-11" "2020-12"

and I wrote the following code:

c(sprintf("2016-d", 1:12), 
  sprintf("2017-d", 1:12),
  sprintf("2018-d", 1:12),
  sprintf("2019-d", 1:12),
  sprintf("2020-d", 1:12))

Is there any other shorter and eleganter solution? For example any suggestion to combine the first part of sprintf?

CodePudding user response:

With base R, try:

seq.Date(from = as.Date("2016-01-01"), to = as.Date("2020-12-01"), by = "1 month") |> format("%Y-%m")

 [1] "2016-01" "2016-02" "2016-03" "2016-04" "2016-05" "2016-06" "2016-07"
 [8] "2016-08" "2016-09" "2016-10" "2016-11" "2016-12" "2017-01" "2017-02"
[15] "2017-03" "2017-04" "2017-05" "2017-06" "2017-07" "2017-08" "2017-09"
[22] "2017-10" "2017-11" "2017-12" "2018-01" "2018-02" "2018-03" "2018-04"
[29] "2018-05" "2018-06" "2018-07" "2018-08" "2018-09" "2018-10" "2018-11"
[36] "2018-12" "2019-01" "2019-02" "2019-03" "2019-04" "2019-05" "2019-06"
[43] "2019-07" "2019-08" "2019-09" "2019-10" "2019-11" "2019-12" "2020-01"
[50] "2020-02" "2020-03" "2020-04" "2020-05" "2020-06" "2020-07" "2020-08"
[57] "2020-09" "2020-10" "2020-11" "2020-12"

CodePudding user response:

1) This will give the indicated character vector or just use ym to get yearmon class vector which may be more convenient as it is represented internally as year fraction where fraction is 0 for Jan, 1/12 for Feb, ..., 11/12 for Dec and so may be manipulated in relevant ways such as using it as the X axis for a plot.

library(zoo)
ym <- seq(as.yearmon("2016-01"),  as.yearmon("2020-12"), 1/12)
format(ym, "%Y-%m")

An alternate way of forming ym is:

ym <- ts(start = 2006, end = c(2012, 12), freq = 12) |> 
  time() |>
  as.yearmon()

2) This would also work using only base R. You might prefer to just use d as it could be used in plotting as well.

d <- seq(as.Date("2016-01-01"), as.Date("2020-12-01"), by = "month")
format(d, "%Y-%m")

3) This base solution is shorter but lacks the flexibility of using Date or yearmon classes.

sprintf("%d-d", rep(2006:2012, each = 12), 1:12)
  •  Tags:  
  • r
  • Related