在R中从字母数字字符中移除前导零

12

我有一个包含字母数字字符的字符向量d

d <- c("012309 template", "separate 00340", "00045", "890 098", "3405 garage", "matter00908")

d
[1] "012309 template" "separate 00340"  "00045"           "890 098"         "3405 garage"     "matter00908"  

如何从R中所有数字中删除前导零?as.numeric仅会移除数字或整数向量中的所有前导零。我尝试了使用regexgsub,但无法得到期望的结果。

期望的输出如下所示:

out <- c("12309 template", "seperate 340", "45", "890 98", "3405 garage", "matter908")
out
[1] "12309 template" "seperate 340"   "45"             "890 98"         "3405 garage"    "matter908"  
2个回答

25
你可以使用负回顾后断言来消除0,除非它前面有数字:
> d <- c("100001", "012309 template", "separate 00340", "00045", "890 098", "3405 garage", "matter00908")
> gsub("(?<![0-9])0+", "", d, perl = TRUE)
[1] "100001"         "12309 template" "separate 340"   "45"            
[5] "890 98"         "3405 garage"    "matter908"     

另一种使用正则表达式的方法:

> gsub("(^|[^0-9])0+", "\\1", d, perl = TRUE)
[1] "100001"         "12309 template" "separate 340"   "45"            
[5] "890 98"         "3405 garage"    "matter908"     
>

这也可以删除数字字符串中的多个零,例如将100001转换为101。 - Crops
2
@Crops 现在应该已经修复了。 - devnull

11

以下是使用stringi包中的stri_replace_all_regex解决方案:

d <- c("012309 template", "separate 00340", "00045",
       "890 098", "3405 garage", "matter00908")
library("stringi")
stri_replace_all_regex(d, "\\b0*(\\d+)\\b", "$1")
## [1] "12309 template" "separate 340"   "45"             "890 98"
## [5] "3405 garage"    "matter00908"   

说明:我们将匹配单词边界内的所有数字序列(\b)。尾随的零被贪婪地匹配(0+)。其余数字(\d表示任何数字,\d+表示它们的非空序列)被捕获在一个组内((...))。然后我们仅用组捕获的内容替换所有这样的匹配。

如果您也希望删除单词内的0(如您的示例中所示),请省略\b并调用:

stri_replace_all_regex(d, "0*(\\d+)", "$1")
## [1] "12309 template" "separate 340"   "45"             "890 98"
## [5] "3405 garage"    "matter908"  

'\d+'是什么意思? - Paulo E. Cardoso
1
\d表示任何数字,\d+表示它们的非空序列 - gagolews

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接