-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
  • 607,720
  • 39
  • 448
  • 563
user42485
  • 751
  • 2
  • 9
  • 19

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
  • 209,562
  • 33
  • 339
  • 356