Home > Back-end >  add a number in the beginning of a value depending on its length
add a number in the beginning of a value depending on its length

Time:11-05

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:

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

CodePudding user response:

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("	d", as.integer(df$Key)) 

using dplyr & stringr

library(dplyr)
library(stringr)
df_desired <- df %>% mutate(Key = str_pad(Key, width = 9, pad = "0"))
  • Related