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