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
  • 4

1 Answers1

0

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
  • 1,874
  • 2
  • 16
  • 30