remove leading 0s with stringr in R

醉酒当歌 提交于 2021-02-16 10:19:11

问题


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

回答1:


Using the new str_remove function in stringr:

id = str_remove(id, "^0+")



回答2:


Here is a base R option using sub:

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

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

Demo




回答3:


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"


来源:https://stackoverflow.com/questions/49186893/remove-leading-0s-with-stringr-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!