我有一个这样的数据帧:
df <- data.frame(
Food = c("Apple", "Banana", "Carrot", "Donut", "Eclair", "Flour"),
Ingredient = c("salt", "sodium chloride", "salt replacer", "unsalted", "veg salt", "vegetable salt")
)
我想使用grepl创建一个变量,该变量在"盐"或"氯化钠"存在时显示为真,而对于其他值"盐替代品"、"无盐"、"素食盐"、"植物盐"则显示为假.
输出应该是如下所示的数据报:
Food | Ingredient | Salt_Present |
---|---|---|
Apple | salt | TRUE |
Banana | sodium chloride | TRUE |
Carrot | salt replacer | FALSE |
Donut | unsalted | FALSE |
Eclair | veg salt | FALSE |
Flour | vegetable salt | FALSE |
为了实现这一点,我在编写正则表达式时遇到了困难.
How can I write a regex that will return true for Apple and Banana, but false for the other cases in the data?个
我还应该补充的是,这是一个玩具示例,在真实数据中,每个成分中都有多个项目.例如,"矿物盐"和"盐"可能出现在同一食物的成分变量中,或者"盐"、"无盐黄油"和"番茄酱".我不确定这是否会改变解决方案,但如果会,可以更新示例数据和输出.