dplyr:根据分组详细信息更改变量

时间:2019-07-09 14:18:55

标签: r dplyr mutate

我想根据同一组中还有哪些其他条目来更新条目。

以玩具示例为例:如果变量both.camp == 0且组中恰好缺少“ C”,我想将“ C”(camp)更改为“ B”(camp_1) “。

玩具数据集:

data <- data.frame(ID=c(1,1,1,0,0,0),date=c(1,1,1,1,1,1),both.camps=c(0,0,0,1,1,1),camp=c("A","A","C","A","B","C"))


  ID date both.camps camp
1  1    1          0    A
2  1    1          0    A
3  1    1          0    C
4  0    1          1    A
5  0    1          1    B
6  0    1          1    C

尝试输入的代码:

data <- data %>% group_by(ID,date) %>% mutate(camp_2=ifelse(both.camps==0 & camp=="C" & !"B" %in% camp ,"B",
                                                              ifelse(both.camps==0 & camp=="C" & !"A" %in% camp, "A", camp)))

理想的结果

desiderata <- data.frame(ID=c(1,1,1,0,0,0),date=c(1,1,1,1,1,1),both.camps=c(0,0,0,1,1,1),camp=c("A","A","C","A","B","C"), camp_2=c("A","A","B","A","B","C"))

  ID date both.camps camp camp_2
1  1    1          0    A      A
2  1    1          0    A      A
3  1    1          0    C      B
4  0    1          1    A      A
5  0    1          1    B      B
6  0    1          1    C      C

1 个答案:

答案 0 :(得分:0)

这可以在较小的数据集上解决问题,我不确定这是否是最好的方法。

namespace App\Something;

class Bitcoin {
    public static doSomething(){}
}