0

One of the columns in my data frame have data like below:

"3,4"  
"9,10"  
"7,8,9"    
"9,10,11,12,13,14"

How do I format it to below format:

"03,04"  
"09,10"  
"07,08,09"  
"9,10,11,12,13,14"  
Rich Scriven
  • 97,041
  • 11
  • 181
  • 245
starter
  • 31
  • 2
  • Possible duplicate of [adding leading zeros using R](http://stackoverflow.com/questions/5812493/adding-leading-zeros-using-r) – arturro Feb 25 '16 at 23:06
  • 1
    If `n <- c(3,4)`, then `sprintf('%02d', n)` gives you `"03" "04"` – Gopala Feb 25 '16 at 23:06
  • Not quite what I wanted. The column is of character datatype with numbers separated by commas. I have updated the question to depict this. – starter Feb 25 '16 at 23:52

1 Answers1

0

We can split the numbers with strsplit, use sprintf after converting the character class to numeric, and finally paste the elements together

sapply(strsplit(df$V1, ','), function(x)
    paste(sprintf("%02d", as.numeric(x)), collapse=","))
#[1] "03,04"             "09,10"             "07,08,09"         
#[4] "09,10,11,12,13,14"

Or without splitting by ,, we can use regex to insert the 0's

gsub('(?<=,)(?=([0-9],|[0-9]$))|^(?=[0-9],)', 
               "0", df$V1, perl=TRUE)
#[1] "03,04"             "09,10"             "07,08,09"          "09,10,11,12,13,14"

data

df <- structure(list(V1 = c("3,4", "9,10", "7,8,9", 
"9,10,11,12,13,14"
)), .Names = "V1", class = "data.frame", 
row.names = c(NA, -4L))
akrun
  • 874,273
  • 37
  • 540
  • 662