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

时间:2015-01-21 14:45:33

标签: r string text-extraction

我有这个例子:

> 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

任何帮助都会很棒: - )

4 个答案:

答案 0 :(得分:3)

以下是使用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的评论,如果您只想匹配完全 11个数字,那么您可以使用:

m <- str_extract(d$V1, perl('(?<!\\d)\\d{11}(?!\\d)'))

答案 1 :(得分:2)

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

答案 2 :(得分:1)

以下是我接近它的方法。这可以在基础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

答案 3 :(得分:0)

您要查找的命令是grep()。在那里使用的模式类似于\d{11}[0-9]{11}

相关问题