1

first of all, I have read through the following posts (R: keep leading zero, and again, and this one, and this one, or this one.), and my question is not answered by any of them.

I try to add a leading zero to the ID column. The file is imported from excel, I am not sure how to upload to here. Probably not able to replicate the process to you.

When I use any of the following code to add a leading zero

formatC(data$col,width=5,format="s",flag="0")
sprintf("%05s",data$col)
gsub('\\s','0',data$col)

all of them gave me a whitespace before the string, instead of a zero. e.g." 4097"

I also try to trim down any spacetrimws(sort$DlrNbr, which = c("both", "left", "right")), and re-try add leading zero, still failed.

Do you have any idea what is going on? Any insight is helpful!

Blundering Ecologist
  • 1,199
  • 2
  • 14
  • 38
C_Mu
  • 305
  • 4
  • 14
  • When asking for help, you should include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Mar 02 '18 at 21:29
  • i will keep that in mind – C_Mu Mar 02 '18 at 21:40

3 Answers3

5

You used the wrong format with sprintf.

Using sprintf('%05d', data$col) should do the trick (notice the d, which is used to format integers, instead of the s, which is used to format strings).

You can find more details in the help page: https://www.rdocumentation.org/packages/base/versions/3.4.3/topics/sprintf

lucacerone
  • 9,859
  • 13
  • 52
  • 80
  • Hey Lucacerone, thank you so much. You solve my problem. I didnt aware I can convert to numeric and add leading zero. thank you! – C_Mu Mar 02 '18 at 21:41
  • Still not working. sprintf('%02s', "1") returns " 1", not "01". – Luke Jul 06 '20 at 09:50
  • df$col<- gsub(" ", "0",df$col ). When set at default I got blanks instead of 0 so I just did a replace. – user35131 Aug 05 '22 at 19:47
2

Using the stringr package:

library(stringr)
str_pad(data$col, 5, pad = "0")
mpalanco
  • 12,960
  • 2
  • 59
  • 67
0

Why not just use paste, i.e.:

library(data.table)
data[, col := paste0('0', col)]
C-x C-c
  • 1,261
  • 8
  • 20
  • Hey, because it should be a fixed width, some id is like 45009, they dont need a leading zero. thank you so much though – C_Mu Mar 02 '18 at 21:31