JustADude
JustADude

Reputation: 2709

R extract numeric values from text

Using R version 3.0.3 (2014-03-06):

When UIM (unique identifying marker), what is the recommended approach for extracting the numeric portion of the string of text? Also, I don't to extract the numeric portion when BAD is present.

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

Unfortunately, I need to maintain traceability back to the row number, i.e. know which rows provided UIM info and which ones didn't.

Thanks a ton for any feedback and info.

Upvotes: 0

Views: 500

Answers (1)

Victorp
Victorp

Reputation: 13856

You can use the package stringr, here the result is a list but it gives what you want :

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

If you want to know which row don't provide info, you can use :

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

EDIT :

If you don't want to use stringr, you can do like sebastian-c say here :

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

Upvotes: 2

Related Questions