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
  • 4

3 Answers3

5

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
  • 147,086
  • 7
  • 49
  • 87
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
  • 72,363
  • 6
  • 19
  • 66
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
  • 17,740
  • 16
  • 106
  • 167