Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove leading 0s with stringr in R

Tags:

r

stringr

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
like image 899
Alex Avatar asked Mar 09 '18 05:03

Alex


People also ask

How do you remove leading zeros from a string?

We recommend using regular expressions and the string replace() method to remove leading zeros from a string.

How do you remove leading zeros from an array?

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.


2 Answers

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"
like image 69
akrun Avatar answered Oct 19 '22 07:10

akrun


Here is a base R option using sub:

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

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

Demo

like image 40
Tim Biegeleisen Avatar answered Oct 19 '22 07:10

Tim Biegeleisen