I have the following data
id
00001
00010
00022
07432
I would like to remove the leading 0
s so the data would like like the following
id
1
10
22
7432
We recommend using regular expressions and the string replace() method to remove leading zeros from a string.
Approach: Mark the first non-zero number's index in the given array. Store the numbers from that index to the end in a different array. Print the array once all numbers have been stored in a different container.
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"
Here is a base R option using sub
:
id <- sub("^0+", "", id)
id
[1] "1" "10" "22" "7432"
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