[英]R/dplyr: Replace row values based on two conditions, keep all others as they are
I have a data set that has a variable fruit and a owner.我有一个具有可变水果和所有者的数据集。 Input:
输入:
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
I want to rename all values in the fruit column if two conditions across the fruit and owner column are met;如果满足水果和所有者列的两个条件,我想重命名水果列中的所有值; the fruit is NOT an apple, and the owner contains a
'
symbol.水果不是苹果,所有者包含一个
'
符号。 I want the end result to look like this:我希望最终结果如下所示:
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
I tried using dplyr, but this data snippet drops all other rows that are not met by the conditions.我尝试使用 dplyr,但此数据片段删除了条件不满足的所有其他行。 I need to keep all rows, and merely replace the values in those where the two conditions are met:
我需要保留所有行,并且只替换满足两个条件的值:
qx2 <- qx %>%
dplyr::filter(grepl("'", Owner)) %>%
dplyr::filter(Fruit != "apple") %>%
dplyr::mutate(Fruit = "carrot")
I also tried this snippet, which doesn't do anything at all:我也试过这个片段,它根本没有做任何事情:
qx2$Fruit[qx2$Fruit== "apple" & qx2$Owner == grepl("'", qx2$Owner)] = "carrot"
Try the vectorized ifelse尝试矢量化 ifelse
library(dplyr)
qx %>%
mutate(Fruit = ifelse(Fruit != "apple" & grepl("'", Owner), "carrot", Fruit))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.