I asked a question like this yesterday, but today I need help doing it in R. You can see the original question here: Create new indicator columns based on values in another column
I have some data that looks like this:
df <- data.frame(col = c('I want an apple', 'i hate pears', 'please buy a peach and an apple', 'I want squash'))
I want it to look like this:
goal_df <- data.frame(col = c('I want an apple', 'i hate pears', 'please buy a peach and an apple', 'I want squash'),
apple = c(1, 0, 1, 0),
pear = c(0, 1, 0, 0),
peach = c(0, 0, 1, 0))
head(goal_df)
col apple pear peach
1 I want an apple 1 0 0
2 i hate pears 0 1 0
3 please buy a peach and an apple 1 0 1
4 I want squash 0 0 0
I tried this:
fruits <- list('apple', 'pear', 'peach')
for (i in fruits){
df$i <- ifelse(str_detect(df$col, i), 1, 0)
}
col x
1 I want an apple 0
2 i hate pears 0
3 please buy a peach and an apple 1
4 I want squash 0
Can someone help me with what I'm doing wrong here? I'm not sure why this is only creating one column.