How to concatenate strings as year of month without using for loops

I have been trying to create strings year,monthfor several years (from 1997 to 20061212). I can do this using for loops, is there a way to do this without using loops?

My goal:

#1997 01 to 2006 12
199701
199702
199703
199704
199705
199706
199707
199708
199709
199710
199711
199712
199801
.....
0
source share
4 answers

This should work

`dim<-`(outer(1997:2006,sprintf("%02d", 1:12),paste0),NULL)
+1
source

Another option:

paste0(rep(1997:2006, each=12), sprintf("%02d", 1:12))
+1
source

We can also use expand.grid

 do.call(paste, c(expand.grid(1997:2006, sprintf('%02d', 
           1:12)), sep='' ) )
0
source

All answers posted so far include separate calls paste()and sprintf()instead of a single call sprintf().

The solution below uses the function CJ()(cross join) from the package data.table:

library(data.table)
CJ(1997:2006, 1:12)[, sprintf("%4i%02i", V1, V2)]
  [1] "199701" "199702" "199703" "199704" "199705" "199706" "199707" "199708" "199709" "199710"
 [11] "199711" "199712" "199801" "199802" "199803" "199804" "199805" "199806" "199807" "199808"
 [21] "199809" "199810" "199811" "199812" "199901" "199902" "199903" "199904" "199905" ...
0
source

All Articles