1 Goal


The goal of this tutorial is to learn how to introduce numbers in a string, filling with zeroes up to a given number. This is useful when creating filenames.


2 Fill string with numbers


# We want to use a numerical vector to create strings
my_vector <- as.character(1:20)
my_vector
##  [1] "1"  "2"  "3"  "4"  "5"  "6"  "7"  "8"  "9"  "10" "11" "12" "13" "14"
## [15] "15" "16" "17" "18" "19" "20"
# However in strings, the order doesn't follow the numerical logic
# First all numbers starting with 1 will appear, then the ones starting with 2, and so on
order(my_vector)
##  [1]  1 10 11 12 13 14 15 16 17 18 19  2 20  3  4  5  6  7  8  9
my_vector[order(my_vector)]
##  [1] "1"  "10" "11" "12" "13" "14" "15" "16" "17" "18" "19" "2"  "20" "3" 
## [15] "4"  "5"  "6"  "7"  "8"  "9"
# If we want the strings to follow the same order than the numbers we need to make changes
# We will introduce zeroes in front of all numbers until the length of the biggest number
# Now the numbers will look like 01, 02, 03, 04, 05, etc

my_vector <- 1:20
my_vector <- as.character(formatC(my_vector, width=2, flag="0"))
my_vector
##  [1] "01" "02" "03" "04" "05" "06" "07" "08" "09" "10" "11" "12" "13" "14"
## [15] "15" "16" "17" "18" "19" "20"
# And now the original order is kept
order(my_vector)
##  [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20
my_vector[order(my_vector)]
##  [1] "01" "02" "03" "04" "05" "06" "07" "08" "09" "10" "11" "12" "13" "14"
## [15] "15" "16" "17" "18" "19" "20"
# We repeat the same exercise with numbers containing 3 cifers
my_vector <- 1:100
my_vector <- as.character(formatC(my_vector, width = 3, flag = "0"))
my_vector
##   [1] "001" "002" "003" "004" "005" "006" "007" "008" "009" "010" "011"
##  [12] "012" "013" "014" "015" "016" "017" "018" "019" "020" "021" "022"
##  [23] "023" "024" "025" "026" "027" "028" "029" "030" "031" "032" "033"
##  [34] "034" "035" "036" "037" "038" "039" "040" "041" "042" "043" "044"
##  [45] "045" "046" "047" "048" "049" "050" "051" "052" "053" "054" "055"
##  [56] "056" "057" "058" "059" "060" "061" "062" "063" "064" "065" "066"
##  [67] "067" "068" "069" "070" "071" "072" "073" "074" "075" "076" "077"
##  [78] "078" "079" "080" "081" "082" "083" "084" "085" "086" "087" "088"
##  [89] "089" "090" "091" "092" "093" "094" "095" "096" "097" "098" "099"
## [100] "100"

3 Conclusion


In this tutorial we have learnt how to add numbers to a string adding the proper amount of zeroes to keep the original order.