在 R 中使用 stringr 删除前导 0

remove leading 0s with stringr in R

我有以下数据

id
00001
00010
00022
07432

我想删除前导 0,这样数据就会像下面这样

id
1
10
22
7432

这是使用 sub 的基础 R 选项:

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

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

Demo

使用 stringr 中的新 str_remove 功能:

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

我们可以转换为numeric

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

如果我们需要 character class 输出,可以使用 stringr 中的 str_replace

library(stringr)
str_replace(df1$id, "^0+" ,"")
#[1] "1"    "10"   "22"   "7432"