【问题标题】:R/dplyr: Replace row values based on two conditions, keep all others as they areR/dplyr:根据两个条件替换行值,保持所有其他条件不变
【发布时间】: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"

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    试试矢量化 ifelse

    library(dplyr)
        qx %>%
           mutate(Fruit = ifelse(Fruit != "apple" & grepl("'", Owner), "carrot", Fruit))
    

    【讨论】:

    • 谢谢!我尝试运行该代码,但收到以下错误消息:Error: Column `Fruit` can't be converted from integer to character - 这很奇怪,因为该列是一个因素。我还尝试使用as.character() 将列转换为字符,但我仍然收到相同的错误消息。我该如何解决这个问题?
    • 没关系,我通过在 dplyr 管道中将列作为字符首先改变来解决它:qx2 &lt;- qx %&gt;% dplyr::mutate(Fruit= as.character(Fruit)) %&gt;% dplyr::mutate(Fruit= ifelse(Fruit!= "apple" &amp; grepl("'", Owner), "carrot", Fruit))
    • 很高兴你知道了!
    猜你喜欢
    • 2018-11-13
    • 2020-11-17
    • 2019-02-12
    • 1970-01-01
    • 2021-03-29
    • 2020-04-24
    • 2020-06-08
    • 2022-12-22
    • 2018-11-29
    相关资源
    最近更新 更多