R从文本中提取数值

时间:2014-04-10 13:36:54

标签: r

使用R版本3.0.3(2014-03-06):

当UIM(唯一识别标记)时,提取文本字符串的数字部分的推荐方法是什么?此外,当存在BAD时,我不提取数字部分。

text_entry<-rbind("Text words UIM 1234, 5678, 9012. More text and words.", #1
      "Text words UIM 2143 6589 1032. More text and words.", #2
    "Text words UIMs 4123 and 8657 and more text and words.", #3
    "Text words BAD 4123 and 8657 and more text and words.", #4
    "Text words UIM-2143, UIM-6589, and UIM-1032. More text and words.", #5
    "Text words BAD-2143, BAD-6589, and BAD-1032. More text and words.", #6
    "Text words UIM that follow: 2143, 6589, and UIM-1032. More text and words.", #7
    "Text words UIM that follow: 2143 1032. More text and words.") #8

Extract_desired:

1234, 5678, 9012 #1
2143, 6589, 1032 #2
4123, 8657 #3
NA (due to BAD) #4
2143, 6589, 1032 #5
NA (due to BAD) #6
2143, 6589, 1032 #7
2143,  1032 #8

不幸的是,我需要将可追溯性保持回行号,即知道哪些行提供了UIM信息,哪些行没有。

非常感谢任何反馈和信息。

1 个答案:

答案 0 :(得分:2)

你可以使用包stringr,这里的结果是一个列表,但它给出了你想要的东西:

library(stringr)
extract_desired <- lapply(text_entry, function(x) {if (!grepl("BAD", x)) unlist(str_extract_all(x, "\\d+"))})
extract_desired[c(1,4)] 

## [[1]]
## [1] "1234" "5678" "9012"

## [[2]]
## NULL

如果您想知道哪一行不提供信息,您可以使用:

which(sapply(extract_desired, is.null))
## [1] 4 6

编辑:

如果你不想使用stringr,你可以像塞巴斯蒂安一样说here

extract_desired <- lapply(text_entry, function(x) {if (!grepl("BAD", x)) unlist(regmatches(x, gregexpr("[[:digit:]]+", x)))})