Use sprintf() to add trailing zeros

前端 未结 3 1935
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-19 03:11

There has to be a simple way of doing this and I am overlooking it. But if I have a series of id and want to add trailing zeros where the character limit is not

相关标签:
3条回答
  • 2020-12-19 04:00

    I don't think sprintf does that, but you can use formatC to do that

    x <- 123    
    formatC(as.numeric(x), format = 'f', flag='0', digits = 2)
    [1] "123.00"
    
    0 讨论(0)
  • 2020-12-19 04:00

    If we insist - we can fool sprintf() into doing what it doesn't want to do:

    # Helper function from: stackoverflow.com/a/13613183/4552295
    strReverse <- function(x) sapply(lapply(strsplit(x, NULL), rev), paste, collapse="")
    
    so_0padr <- function(x, width = 5) {
      strReverse(
        sprintf(
          "%0*d",
          width,
          as.integer(
            strReverse(
              as.character(x)
            )
          )
        )
      )
    }
    

    Resulting in

    so_0padr(c(2331,29623,311,29623))
    [1] "23310" "29623" "31100" "29623"
    
    0 讨论(0)
  • 2020-12-19 04:05

    As noted in the comments, sprintf() won't do this. But the stringi package has padding functions that are quick and easy.

    id <- c(2331, 29623, 311, 29623)
    
    library(stringi)
    stri_pad_left(id, 5, 0)
    # [1] "02331" "29623" "00311" "29623"
    stri_pad_right(id, 5, 0)
    # [1] "23310" "29623" "31100" "29623"
    

    These functions dispatch directly to C code, so they should be sufficiently efficient.

    0 讨论(0)
提交回复
热议问题