Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add 0 before a single digit to a column

I have dataframe with several columns like this with str character

df$A <- c("1, 26, 61", "2, 3", "2, 68", "2", "2, 3", "3, 11")

I want to add 0 before a single-digit only

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I have tried these codes but I am not getting desired output like this

output= "01, 26, 61", "02, 03", "02, 68", "02", "02, 03", "03, 11"


df$A <- sprintf("%02s",df$A)
df$A <- str_pad(df$A, width=2, pad=0)
stringr::str_pad(df, 2, side="left", pad="0")

>Solution :

Maybe you can try

> x <- c("1, 26, 61", "2, 3", "2, 68", "2", "2, 3", "3, 11")

> gsub("\\b(\\d)\\b", "0\\1", x)
[1] "01, 26, 61" "02, 03"     "02, 68"     "02"         "02, 03"
[6] "03, 11"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading