convert digits to special format

Question

In my data processing, I need to do the following:

    #convert '7-25' to '0007 0025'
    #pad 0's to make each four-digit number 
    digits.formatter <- function ('7-25'){.......?}

I have no clue how to do that in R. Can anyone help?


Show source
| r   2017-09-05 22:09 3 Answers

Answers to convert digits to special format ( 3 )

  1. 2017-09-05 22:09

    In base R, split the character string (or vector of strings) at -, convert its parts to numeric, format the parts using sprintf, and then paste them back together.

    sapply(strsplit(c("7-25", "20-13"), "-"), function(x)
        paste(sprintf("%04d", as.numeric(x)), collapse = " "))
    #[1] "0007 0025" "0020 0013"
    
  2. 2017-09-05 22:09

    A solution with stringr:

    library(stringr)
    
    digits.formatter <- function(string){
      str_vec = str_split(string, "-")
      output = sapply(str_vec, function(x){
        str_padded = str_pad(x, width = 4, pad = "0")
        paste(str_padded, collapse = " ")
      })
      return(output)
    }
    
    digits.formatter(c('7-25', '8-30'))
    # [1] "0007 0025" "0008 0030"
    

    The pad= argument in str_pad specifies whatever you like to pad, whereas width= specifies the minimum width of the padded string. You can also use an optional argument side= to specify which side you want to pad the string (defaults to side=left). For example:

    str_pad(1:5, width = 4, pad = "0", side = "right")
    # [1] "1000" "2000" "3000" "4000" "5000"
    
  3. 2017-09-06 06:09

    We could do this with gsubfn

    library(gsubfn)
    gsubfn("(\\d+)", ~sprintf("%04d", as.numeric(x)), v1)
    #[1] "0007-0025" "0020-0013"
    

    If we don't need the -,

    either use sub after the gsubfn

    sub("-", " ", gsubfn("(\\d+)", ~sprintf("%04d", as.numeric(x)), v1))
    #[1] "0007 0025" "0020 0013"
    

    or directly use two capture groups in gsubfn

    gsubfn("(\\d+)-(\\d+)", ~sprintf("%04d %04d", as.numeric(x), as.numeric(y)), v1)
    #[1] "0007 0025" "0020 0013"
    

    data

    v1 <- c("7-25", "20-13")
    

Leave a reply to - convert digits to special format

◀ Go back