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
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")
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"
Splitting each string, padding, and then pasting back together again will allow a degree of flexibility, at the cost of some more complexity:
A <- c("1, 26, 61", "2, 3", "2, 68", "2", "2, 3", "3, 11")
sapply(strsplit(A, ",\\s+"),
\(x) paste(sprintf("%02d", as.numeric(x)), collapse=", "))
## or as Thomas notes in the comments, if the comma separated output is sufficient:
sapply(strsplit(A, ",\\s+"),
\(x) toString(sprintf("%02d", as.numeric(x))))
Both giving:
##[1] "01, 26, 61" "02, 03" "02, 68" "02" "02, 03"
##[6] "03, 11"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With