Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

stringr::str_extract all elements of a list R

I’m trying to get all the "banana + word" ocurrences of a given object, but the str_extract returns only the first occurence. My code:

all_terms <- c("banana word2 word3 word4 banana split word2 word3 word4",
               "x y z",
               "banana ice cream")

banana_terms <- all_terms %>% 
  str_extract("banana.+") %>% 
  word(1,2)


banana_terms
Out: [1] "banana word2" NA             "banana ice"  

What I wanted:

Out: [1] "banana word2" "banana split", "banana ice" 

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use str_extract_all and \\w+ to get the word after banana (and banana).

all_terms %>% 
  str_extract_all("banana.\\w+") %>% 
  unlist()

# [1] "banana word2" "banana split" "banana ice"

Without unlist, you get a list:

str_extract_all(all_terms, "banana.\\w+")

[[1]]
[1] "banana word2" "banana split"

[[2]]
character(0)

[[3]]
[1] "banana ice"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading