从字符串中提取和合并数字

3

我有一些包含数字的字符串如下:

972 2 6424979
81|5264627
49-0202-2801986
07.81.48.27.89
0664/3420034
06041 - 8728

我希望你能够输出如下内容:

97226424979
815264627
4902022801986
0781482789
06643420034
060418728

我尝试使用:

as.numeric(gsub("([0-9]+).*$", "\\1", numbers))

但输出的数字是分开显示的。

1
as.numeric(gsub('\\D+', '', numbers)) - Sotos
@Sotos,由于某种原因,输出中不显示以0开头的数字。 - Mattematics
它以科学计数法显示数字,并在转换为“numeric”时预计不会出现前导0。我得到的结果是:[1] 9.722642e+10 8.152646e+08 4.902023e+12 7.814828e+08 6.643420e+09 6.041873e+07 - Sotos
2个回答

1
为了得到您精确的输出,
#to avoid scientific notation
options(scipen=999)

#find which have leading 0
ind <- which(substring(x, 1, 1) == 0)

y <- as.numeric(gsub("\\D", "", numbers))
y[ind] <- paste0('0', y[ind])
y
#[1] "97226424979"   "815264627"     "4902022801986" "0781482789"    "06643420034"   "060418728"

0

([0-9]+).*$ 将数字序列放入 \\1 直到第一个非数字。但是,您想要:

numbers <- readLines(n=6)
972 2 6424979
81|5264627
49-0202-2801986
07.81.48.27.89
0664/3420034
06041 - 8728
as.numeric(gsub("\\D", "", numbers))

这将所有非数字替换为空。


如果科学计数法确实困扰了OP,可以使用此链接中提供的方法禁用它。 - Sotos

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