3

how would I be able to go from a column like this: 1 1 1 2 3 4 9 25 100

to one like this: 01 01 01 02 03 04 09 25 100

Basically, I want to add a leading zero to any value with only length 1. The actual data frame is much bigger than this. Thanks!

Stacy
  • 87
  • 3

3 Answers3

4

You can use sprintf in base R

vec <-  c(1, 1, 1, 2, 3, 4, 9, 25, 100)

sprintf("%02d", vec)
#> [1] "01"  "01"  "01"  "02"  "03"  "04"  "09"  "25"  "100"
Allan Cameron
  • 91,771
  • 6
  • 28
  • 55
3

As an alternative str_pad from stringr package:

library(stringr)
str_pad(vec, 2, pad = "0")
[1] "01"  "01"  "01"  "02"  "03"  "04"  "09"  "25"  "100"
TarJae
  • 43,365
  • 4
  • 14
  • 40
0

You may also want to explore the formatC function:

vec <-  c(1, 1, 1, 2, 3, 4, 9, 25, 100)
formatC(x = vec, digits = 1, flag = "0", format = "d")

Results

"01"  "01"  "01"  "02"  "03"  "04"  "09"  "25"  "100"
Konrad
  • 16,498
  • 15
  • 94
  • 152