昨天我问了一个类似的问题,但今天我需要帮助用R进行操作。你可以在这里查看原始问题:Create new indicator columns based on values in another column
我的数据是这样的:
df <- data.frame(col = c('I want an apple', 'i hate pears', 'please buy a peach and an apple', 'I want squash'))
我希望它看起来像这样:
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
我尝试了这个:
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
有人能帮我看看我做错了什么吗?不确定为什么这只创建了一列。