Luke
Luke

Reputation: 7089

Change value of a column based on whether string is in another column using R

I want to create a new column based on whether a string is present in a different column of the dataframe.

 name
  Jon
  Anne
Jobraith
  Knut

Becomes:

 name      dummy
  Jon        1
  Anne       0
Jobraith     1
  Knut       0

looking for something along the lines of:

df$dummy <- ifelse('jo' in df$name, 1, 0)

Upvotes: 1

Views: 1437

Answers (1)

hwnd
hwnd

Reputation: 70722

You could use grepl( ... ) to check for the substring ...

df <- data.frame(name = c('Jon', 'Anne', 'Jobraith', 'Knut'))
df$dummy <- as.numeric(grepl('jo', df$name, ignore.case=T))
df

#       name dummy
# 1      Jon     1
# 2     Anne     0
# 3 Jobraith     1
# 4     Knut     0

Upvotes: 3

Related Questions