我有一个带字母数字字符的字符向量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将仅在数字或整数向量中删除所有前导零.我已尝试使用正则表达式gsub但无法获得所需的结果.
预期输出如下
out <- c("12309 template","seperate 340","45","890 98","matter908") out [1] "12309 template" "seperate 340" "45" "890 98" "3405 garage" "matter908"
你可以使用负向lookbehind来消除0,除非前面有一个数字:
> d <- c("100001","012309 template","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",perl = TRUE) [1] "100001" "12309 template" "separate 340" "45" [5] "890 98" "3405 garage" "matter908" >