r - 根据另一个单元格中的值操作组内的单元格
问题描述
我有以下格式的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)
感谢任何评论/反馈。
解决方案
在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")
推荐阅读
- android - 我应该在 Singleton 类中处理一次性用品吗(Android RxJava 2)
- git - 如何删除 git 中不完整的拉取文件?
- semantic-web - 公证领域的本体
- ios - Swift 4. 能否建议您在返回应用后如何播放视频?
- javascript - 如何在Javascript中获取给定日期,时间和区域的时间戳
- javascript - 激活引导折叠时切换 Inline Chevron Down
- hyperledger-composer - 错误:尝试 ping 时出错。错误:2 UNKNOWN:确保链码
- c# - 有什么区别,为什么 Switch Case 在 C# 中这样工作?
- docker - 我使用 nvdidia-docker 使用 nvidia-docker 中的 nvidia/cuda 映像安装 mysql5.7。发现mysql服务无法启动
- javascript - Webpack 无冗余导出所有组件