Adds n leading zeros to a vector so that each element of the vector has the same number of characters. See examples below.
leading_zero(x)
a character
or a numeric
vector.
A character
vector of the same length as x
.
## On numeric vector ----
x <- 1:10
leading_zero(x)
#> [1] "01" "02" "03" "04" "05" "06" "07" "08" "09" "10"
x <- 50:100
leading_zero(x)
#> [1] "050" "051" "052" "053" "054" "055" "056" "057" "058" "059" "060" "061"
#> [13] "062" "063" "064" "065" "066" "067" "068" "069" "070" "071" "072" "073"
#> [25] "074" "075" "076" "077" "078" "079" "080" "081" "082" "083" "084" "085"
#> [37] "086" "087" "088" "089" "090" "091" "092" "093" "094" "095" "096" "097"
#> [49] "098" "099" "100"
## On floating vector ----
x <- c(1, 9.5, 10, 10.2)
leading_zero(x)
#> [1] "01.0" "09.5" "10.0" "10.2"
## On character vector ----
x <- as.character(1:10)
leading_zero(x)
#> [1] "01" "02" "03" "04" "05" "06" "07" "08" "09" "10"
## Creating sortable identifiers ----
x1 <- as.character(10:1)
x2 <- leading_zero(x)
sort(x1)
#> [1] "1" "10" "2" "3" "4" "5" "6" "7" "8" "9"
sort(x2)
#> [1] "01" "02" "03" "04" "05" "06" "07" "08" "09" "10"
x2 <- paste0("ID", x2)
sort(x2)
#> [1] "ID01" "ID02" "ID03" "ID04" "ID05" "ID06" "ID07" "ID08" "ID09" "ID10"