17

I have a dataframe that looks like this:

A     B
ABC1  0
DEF2  4
DEG0  4

How do I transform this so that if a row contains the letter "D" then insert the value "yes" in a new column and "no" if not.

Final dataframe should look like this:

A     B    C
ABC1  0    no
DEF2  4    yes
DEG0  4    yes
oguz ismail
  • 39,105
  • 12
  • 41
  • 62
nak5120
  • 3,793
  • 4
  • 28
  • 73

1 Answers1

31

We can use grepl to return a logical index by matching the 'D' in the 'A' column, and then with ifelse, change the logical vector to 'yes' and 'no'

df$C <- ifelse(grepl("D", df$A), "yes", "no")
akrun
  • 789,025
  • 32
  • 460
  • 575