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 a number in the beginning of a value depending on its length

Based on the data below how can I tell R to add 0 in the beginning of a value (column key) if its length is less than 9?

Sample data:

id = c(1,2,3,4,5,6,7,8,9,10)
Key = c("10032012", "10812012", "2073017", "10692013", "10892012", "10952014", "10972012", "560392013", "560372013", "56022012")

df = data.frame(id, Key)

Desired Output:

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

df_desired = structure(list(id = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), Key = c("010032012", 
"010812012", "02073017", "010692013", "010892012", "010952014", "010972012", 
"560392013", "560372013", "56022012")), class = "data.frame", row.names = c(NA, 
-10L))

>Solution :

Some answers
For any character string:

df$Key <- ifelse(nchar(df$Key) < 9, paste0("0", df$Key), df$Key)

If they are all integer strings a canonical way would be:

df$Key <- sprintf("%09d", as.integer(df$Key)) 

using dplyr & stringr

library(dplyr)
library(stringr)
df_desired <- df %>% mutate(Key = str_pad(Key, width = 9, pad = "0"))
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