20

I have the following data

id
00001
00010
00022
07432

I would like to remove the leading 0s so the data would like like the following

id
1
10
22
7432
Alex
  • 2,603
  • 4
  • 40
  • 73

3 Answers3

34

Using the new str_remove function in stringr:

id = str_remove(id, "^0+")
Marius
  • 58,213
  • 16
  • 107
  • 105
13

We can just convert to numeric

as.numeric(df1$id)
[#1]    1   10   22 7432

If we require a character class output, str_replace from stringr can be used

library(stringr)
str_replace(df1$id, "^0+" ,"")
#[1] "1"    "10"   "22"   "7432"
akrun
  • 874,273
  • 37
  • 540
  • 662
  • What does the "^0+" part mean? – Basil Feb 08 '21 at 10:52
  • 1
    @Basil The `+` implies one or more, so if the 0 is prefix, it would be one or more zeros and the `^` suggest the start of the string. Therefore, the pattern checked is one or more zeros as the beginning of a string – akrun Feb 08 '21 at 16:16
12

Here is a base R option using sub:

id <- sub("^0+", "", id)
id

[1] "1"    "10"   "22"   "7432"

Demo

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360