1

I have list of numbers :

> list1 <- c(1:10, 100, 1000)
> list1
 [1]    1    2    3    4    5    6    7    8    9   10  100 1000

I want to prefix numbers with zeros with respect to largest number in the list. I've done this function:

prefix.zeros  <- function(VECTOR){
  max_length   <- nchar(max(VECTOR))
  retval       <- vector()

  for (i in 1:length(VECTOR)){
    prefix     <- vector()
    cur_length <- nchar(VECTOR[i])

    for(j in cur_length:(max_length-1)){
      if (cur_length == max_length){
        prefix <- ""
      }
      else if (cur_length < max_length){
        prefix <- c(prefix,"0")
      }
    }
    retval <- c(retval, paste0(paste0(prefix, collapse = ""), VECTOR[i], collapse = ""))
  }
  retval
}

Which is working fine:

> prefix.zeros(list1)
 [1] "0001" "0002" "0003" "0004" "0005" "0006" "0007" "0008" "0009" "0010" "0100"
[12] "1000"

But I'm wondering if there is more elegant (R-way) approach?

Wakan Tanka
  • 7,542
  • 16
  • 69
  • 122

1 Answers1

4
sprintf(paste0("%0", max(nchar(list1)), "d"), list1)
# [1] "0001" "0002" "0003" "0004" "0005" "0006" "0007" "0008" "0009" "0010" "0100" "1000"
Julius Vainora
  • 47,421
  • 9
  • 90
  • 102