-1

I have a list of numbers (used as characters), for instance,

IDs <- as.character(c('0', '01', '002'))

that I would like to add '0's to, to make so that they all have the same number of characters (3). How can I do this?

IDs2 <- c('000', '001', '002')
Wiktor Stribiżew
  • 561,645
  • 34
  • 376
  • 476
user42485
  • 651
  • 2
  • 8
  • 17

1 Answers1

3

You can use stringr::str_pad:

library(stringr)
IDs <- as.character(c('0', '01', '002')) 

str_pad(IDs, width = 3, pad = '0')
# [1] "000" "001" "002"

Or use sprintf:

sprintf('%03s', IDs)
# [1] "000" "001" "002"
Psidom
  • 195,464
  • 25
  • 298
  • 322