Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect a list of words in a string variable and extract matched words to a new variable in data frame

Tags:

r

dplyr

stringr

I have a two variable dataframe one of which is a character vector. Each row in "MyVector" contains a string with exactly one name (i.e. "Pete"). The name can vary in its location in the character string. I want to create code that will match the name in a list with the name in the character string and extract that name into a new variable in the dataframe. If the name was always in the same position in the vector "MyVector", I would create a new variable as a substring of MyVector pulling out the name into a new column. I tried various version of str_detect from Stringr to no avail.

Challenge: How do I detect or extract the name into a new variable and place it into MyDF if the name is in multiple positions?

#Create the data frame
var.1 <-rep(c(1,5,3),2)

MyVector <- c("I know Pete", "Jerry has a new job","Victor is an employee","How to work with Pete","Too Many Students","Bob is mean")
   MyDF <-as.data.frame(cbind(var.1,MyVector))

#Create a vector of a list of names I want to extract into a new column in the dataframe.
Extract <- c("Jerry","Pete", "Bob", "Victor")

#Match would be perfect if I could use it on character vectors
MyDF$newvar <-match(MyDF$MyVector,Extract)

My final data.frame should look something like the output below.

 var.1                     MyVector NEWVAR
1     1               Don knows Pete   Pete
2     5          Jerry has a new job  Jerry
3     3 Victor and Bob are employees Victor
4     1        How to work with Pete   Pete
5     5            Too Many Students     NA
6     3                  Bob is mean    Bob
like image 588
RareAir Avatar asked Aug 10 '16 17:08

RareAir


1 Answers

We can use str_extract after pasteing the 'Extract' together

library(stringr)
MyDF$NEWVAR <- str_extract(MyDF$MyVector, paste(Extract, collapse="|"))
MyDF$NEWVAR
#[1] "Pete"   "Jerry"  "Victor" "Pete"   NA       "Bob"   
like image 167
akrun Avatar answered Nov 09 '22 02:11

akrun