jeudi 24 octobre 2019

R: Update Column Based on Text Condition from Another Column

I would like to make a new column in my data frame by using a conditional statement that would say "If Column_y contains Column_x then 1 else 0"

For example:

Name    Winner   Loser    New Column
John    James    John     0
John    John     James    1
Sarah   Sarah    Carol    1
Steven  Bob      Steven   0 
Dave    Dave     Eric     1
Dave    Dave     Eric     1

I want to have New Column<- "If Winner contains Name then 1 else 0"

Keep in mind this is for 100,000 rows and probably 700 unique names. When I try things like

df$NewColumn<-ifelse(grepl(df$Name,df$Winner)==TRUE,1,0) 

or variations I get the "pattern has a length > 1" error.

Aucun commentaire:

Enregistrer un commentaire