简体   繁体   中英

Looping in R to only add leading zeros to specified length

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

Thanks!

You can use sprintf<\/code> 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"

As an alternative str_pad<\/code> from stringr<\/code> package:

library(stringr)
str_pad(vec, 2, pad = "0")

You may also want to explore the formatC<\/code><\/a> function:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM