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 leading zeros only if the number starts with 6 in R dataframe

I have a dataframe with numbers that I need to format. How do I add leading zeroes to only numbers that starts with 6? All examples seen using str_pad() or sprintf() are not exactly like my task, and I found it challenging to adapt them. My dummy dataframe is below:

dummy_numbers
621103 
06102658  
19562106    
61102
0635467

The desired result is:

desired_numbers
0621103 
06102658  
19562106    
061102
0635467

Thanks.

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

>Solution :

Your can use grepl() and regex (^) to capture the start of a string.

library(tidyverse)

df %>% mutate(dummy_numbers = ifelse(grepl("^6", dummy_numbers), 
                                     paste0(0, dummy_numbers), 
                                     dummy_numbers))
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