从R中的字符串中提取特定数字

Extract specific numbers from string in R

我有这个例子:

> exemplo
V1   V2
local::/raiz/diretorio/adminadmin/    1
local::/raiz/diretorio/jatai_p_user/    2
local::/raiz/diretorio/adminteste/    3
local::/raiz/diretorio/adminteste2/    4
local::/raiz/diretorio/48808032191/    5
local::/raiz/diretorio/85236250110/    6
local::/raiz/diretorio/92564593100/    7
local::/raiz/diretorio/AACB/036/03643936451/  331
home::22723200159 3894
home::98476963300 3895
home::15239136149 3896
home::01534562567 3897

我只想提取恰好包含 11 个字符的数字(在第一列中),生成如下所示的结果:

> exemplo
V1   V2
48808032191    5
85236250110    6
92564593100    7
03643936451   331
22723200159   3894
98476963300   3895
15239136149   3896
01534562567   3897

任何帮助都会很棒 :-)

您要查找的命令是grep()。使用的模式应该是 \d{11}[0-9]{11}.

这是使用 stringr 的一种方法,其中 d 是您的数据框:

library(stringr)
m <- str_extract(d$V1, '\d{11}')
na.omit(data.frame(V1=m, V2=d$V2))

#             V1   V2
# 5  48808032191    5
# 6  85236250110    6
# 7  92564593100    7
# 8  03643936451  331
# 9  22723200159 3894
# 10 98476963300 3895
# 11 15239136149 3896
# 12 01534562567 3897

上述方法将匹配至少 11 个数字的字符串。回应@JoshO'Brien 的评论,如果你只想匹配 exactly 11 个数字,那么你可以使用:

m <- str_extract(d$V1, perl('(?<!\d)\d{11}(?!\d)'))
DF <- read.table(text = "V1   V2
local::/raiz/diretorio/adminadmin/    1
local::/raiz/diretorio/jatai_p_user/    2
local::/raiz/diretorio/adminteste/    3
local::/raiz/diretorio/adminteste2/    4
local::/raiz/diretorio/48808032191/    5
local::/raiz/diretorio/85236250110/    6
local::/raiz/diretorio/92564593100/    7
local::/raiz/diretorio/AACB/036/03643936451/  331
home::22723200159 3894
home::98476963300 3895
home::15239136149 3896
home::01534562567 3897", header = TRUE)


pattern <- "\d{11}"
m <- regexpr(pattern, DF$V1)
DF1 <- DF[attr(m, "match.length") > -1,]
DF1$V1<- regmatches(DF$V1, m)

#            V1   V2
#5  48808032191    5
#6  85236250110    6
#7  92564593100    7
#8  03643936451  331
#9  22723200159 3894
#10 98476963300 3895
#11 15239136149 3896
#12 01534562567 3897

以下是我的处理方法。这可以在 base R 中完成,但 stringi 命名的一致性使其易于使用,更不用说它的速度了。我会将 11 位数字存储为新列而不是覆盖旧列。

dat <- read.table(text="V1   V2
local::/raiz/diretorio/adminadmin/    1
local::/raiz/diretorio/jatai_p_user/    2
local::/raiz/diretorio/adminteste/    3
local::/raiz/diretorio/adminteste2/    4
local::/raiz/diretorio/48808032191/    5
local::/raiz/diretorio/85236250110/    6
local::/raiz/diretorio/92564593100/    7
local::/raiz/diretorio/AACB/036/03643936451/  331
home::22723200159 3894
home::98476963300 3895
home::15239136149 3896
home::01534562567 3897", header=TRUE)


library(stringi)
dat[["V3"]] <- unlist(stri_extract_all_regex(dat[["V1"]], "\d{11}"))
dat[!is.na(dat[["V3"]]), 3:2]

##             V3   V2
## 5  48808032191    5
## 6  85236250110    6
## 7  92564593100    7
## 8  03643936451  331
## 9  22723200159 3894
## 10 98476963300 3895
## 11 15239136149 3896
## 12 01534562567 3897