【发布时间】:2020-05-20 14:49:56
【问题描述】:
我有一个包含可变水果和所有者的数据集。 输入:
ID Fruit Owner
1 apple Jane
2 orange Jane's dog
3 cherry John
4 apple John's cat
5 orange John
6 cherry Jane's dog
如果满足fruit和owner列的两个条件,我想重命名fruit列中的所有值;水果不是苹果,所有者包含' 符号。我希望最终结果如下所示:
ID Fruit Owner
1 apple Jane
2 carrot Jane's dog
3 cherry John
4 apple John's cat
5 orange John
6 carrot Jane's dog
我尝试使用 dplyr,但是这个数据 sn-p 删除了所有其他不符合条件的行。我需要保留所有行,只需替换满足两个条件的值:
qx2 <- qx %>%
dplyr::filter(grepl("'", Owner)) %>%
dplyr::filter(Fruit != "apple") %>%
dplyr::mutate(Fruit = "carrot")
我也试过这个sn-p,它根本不做任何事情:
qx2$Fruit[qx2$Fruit== "apple" & qx2$Owner == grepl("'", qx2$Owner)] = "carrot"
【问题讨论】: