I am aware of all of the questions regarding the Adding leading zero
and the comprehensive responses provided for them such as Q1, Q2, Q3.
But to me , at least based on my current knowledge, I am not able to address what I am going to do as follow:
- add the
leading zero
in astring
usingregex
pattern match So, I want to addleading zero
only todigits
after the-
.
for example :
Sam <- c("222-88", "537-457", "652-1", "787-892")
var <- LETTERS[1:4]
DF<- data.frame(Sam, var)
DF
Sam var
1 222-88 A
2 537-457 B
3 652-1 C
4 787-892 D
Expected results:
Sam var
1 222-088 A
2 537-457 B
3 652-001 C
4 787-892 D
I tried :
library(stringr)
temp <- DF[str_detect(DF$Sam, "-[0-9]{1,2}$"),] # will find the rows need the leading zero
temp
Sam var
1 222-88 A
3 652-1 C
formatC(temp$Sam, width = 2,flag = 0)# not correct!