Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add 0 before a single digit to a column

Tags:

string

r

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")
like image 305
Pawan Raghav Avatar asked Dec 12 '25 00:12

Pawan Raghav


2 Answers

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"
like image 102
ThomasIsCoding Avatar answered Dec 13 '25 15:12

ThomasIsCoding


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"  
like image 42
thelatemail Avatar answered Dec 13 '25 14:12

thelatemail