zesla
zesla

Reputation: 11793

convert digits to special format

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?

Upvotes: 4

Views: 68

Answers (3)

akrun
akrun

Reputation: 887168

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")

Upvotes: 0

acylam
acylam

Reputation: 18681

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"

Upvotes: 3

d.b
d.b

Reputation: 32548

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"

Upvotes: 6

Related Questions