Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert digits to special format

Tags:

r

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?

like image 981
zesla Avatar asked Jan 04 '23 12:01

zesla


1 Answers

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"
like image 53
d.b Avatar answered Jan 06 '23 01:01

d.b