0

I have a data frame with this kind of information:

ID    DESCRIPTION   
1     aaabccdd       
2     abcdFOOsajd    
3     1243abcsd      
4     abc123FOO      

I want to add a third column which is going to receive the value 1 if the description has "*FOO*" on it, to get something like this:

ID    DESCRIPTION    TARGET
1     aaabccdd       0
2     abcdFOOsajd    1
3     1243abcsd      0
4     abc123FOO      1

I tried:

df$TARGET <- ifelse(df$DESCRIPTION == grep("FOO", df$DESCRIPTION), "1", "0")

Error in `==.default`(df$DESCRIPTION, grep("FOO", df$DESCRIPTION)) :
  longer object length is not a multiple of shorter object length

And also:

df$TARGET <- ifelse(grep("FOO", df$DESCRIPTION)==TRUE, "1", "0")

Error in `$<-.data.frame`(`*tmp*`, "TARGET", value = c("0", "0", "0",  : 
  replacement has 826768 rows, data has 34035650

Any help on this? I saw other questions about this on SO, but they where on the situation when the if statement is just checking if it's perfectly equal something or a number greater than the other.

Lucas Mattos
  • 175
  • 1
  • 2
  • 5

1 Answers1

1

grepl() is like grep but returns a logical vector (exactly what you want) instead of a vector indicating the indices. As such, you can simply do:

df$TARGET <- grepl("FOO", df$DESCRIPTION)
Barker
  • 2,074
  • 2
  • 17
  • 31
  • 1
    Can wrap it in as.integer to get the OP's desired 1/0 values. – Frank Mar 06 '17 at 21:16
  • Thanks! This worked! And with the help of Frank, we're able to do it with just one line `df$TARGET <- as.integer(grepl("FOO", df$DESCRIPTION))` – Lucas Mattos Mar 06 '17 at 21:36
  • 1
    technically it would be `as.character(as.integer(grepl("FOO", df$DESCRIPTION)))` since the examples output `"1"` and `"0"`. – Barker Mar 06 '17 at 21:38