首页 > 解决方案 > 根据另一个单元格中的值操作组内的单元格

问题描述

我有以下格式的data.frame:

CowId    Bacillus    Week
1234     1           Week1
1234     0           Week2
1234     0           Week3
1234     0           Week4

如果一头奶牛在第 1 周是芽孢杆菌阳性(是=1,否=0),那么我想将此列中的剩余值更改为 1,如下所示:

CowId    Bacillus    Week
1234     1           Week1
1234     1           Week2
1234     1           Week3
1234     1           Week4

我尝试了以下方法,但在确定第 1 周奶牛的感染状态后不确定如何进行:

dt %>%
    group_by(CowId) %>%
    mutate(Bacillus = ifelse(Week == "Week1" & Bacillus, 1,
                          ifelse(Week != "Week1" do something)

感谢任何评论/反馈。

标签: rdplyrtidyverse

解决方案


base R中,我们可以用 'Bacillus' 和 'Week' 创建一个逻辑向量&,其值为 'Week1',子集 'CowId',检查它是否在 'CowId' 中,将逻辑强制转换为二进制 ( +)

df$Bacillus <- with(df, +(CowId %in% unique(CowId[as.logical(Bacillus) &
           Week == 'Week1'])))
df$Bacillus
#[1] 1 1 1 1 0 0 0 0

数据

df <- structure(list(CowId = c(1234, 1234, 1234, 1234, 1235, 1235, 
1235, 1235), Bacillus = c(1, 0, 0, 0, 0, 0, 0, 0), Week = c("Week1", 
"Week2", "Week3", "Week4", "Week1", "Week2", "Week3", "Week4"
)), row.names = c(NA, -8L), class = "data.frame")

推荐阅读