How to add leading zeros?

后端 未结 8 1866
一生所求
一生所求 2020-11-21 05:23

I have a set of data which looks something like this:

anim <- c(25499,25500,25501,25502,25503,25504)
sex  <- c(1,2,2,1,2,1)
wt   <- c(0.8,1.2,1.0,2.         


        
相关标签:
8条回答
  • 2020-11-21 05:52

    Expanding on @goodside's repsonse:

    In some cases you may want to pad a string with zeros (e.g. fips codes or other numeric-like factors). In OSX/Linux:

    > sprintf("%05s", "104")
    [1] "00104"
    

    But because sprintf() calls the OS's C sprintf() command, discussed here, in Windows 7 you get a different result:

    > sprintf("%05s", "104")
    [1] "  104"
    

    So on Windows machines the work around is:

    > sprintf("%05d", as.numeric("104"))
    [1] "00104"
    
    0 讨论(0)
  • 2020-11-21 05:52

    Here's a generalizable base R function:

    pad_left <- function(x, len = 1 + max(nchar(x)), char = '0'){
    
        unlist(lapply(x, function(x) {
            paste0(
                paste(rep(char, len - nchar(x)), collapse = ''),
                x
            )
        }))
    }
    
    pad_left(1:100)
    

    I like sprintf but it comes with caveats like:

    however the actual implementation will follow the C99 standard and fine details (especially the behaviour under user error) may depend on the platform

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