r - 根据其他两列的值更改 R 中列的值
问题描述
我正在尝试根据另外两列的值更改一列的值。到目前为止,这让我有点头疼,我不确定这是否可能。
我的数据集看起来像这样。一列是时间,另外两列反映子代父代关系。在时间点 1 等奇怪的情况下,我的后代“D”第一次出现在数据集中,并且在上一个时间点还没有同时充当后代和父亲时间。
数据
structure(list(time = c(0L, 0L, 0L, 1L, 1L, 1L, 2L, 2L, 2L),
offspring = c("A", "B", "C", "A", "D", "E", "A", "F", "G"
), parent = c(NA, NA, NA, "A", "B", "D", "A", "A", "F")), class = "data.frame", row.names = c(NA,
-9L))
我想要帮助的是
找到存在于一个时间点但不存在于前一个时间点的所有后代(不考虑时间点 0),并像 D 和 F 一样作为后代和父亲
当我找到它们时,我想将一个确切的时间点减少 0.5
time offspring parent
0 A NA
0 B NA
0 C NA
1 A A
0.5 D B
1 E D
2 A A
1.5 F A
2 G F
对此问题的任何帮助或指导将不胜感激。
解决方案
创建 2 个数据框,查找每只动物作为父母和后代的第一次出现。
查找两个组合列中出现的时间和动物,然后更新原始数据框中的时间。
df <-structure(list(time = c(0L, 0L, 0L, 1L, 1L, 1L, 2L, 2L, 2L),
offspring = c("A", "B", "C", "A", "D", "E", "A", "F", "G"),
parent = c(NA, NA, NA, "A", "B", "D", "A", "A", "F")), class = "data.frame",
row.names = c(NA, -9L))
library(dplyr)
#find the row where each Letter First appears as both a parent and offspring
parents <-df %>% filter(complete.cases(.)) %>% group_by(parent) %>% slice(1) %>% select(time, parent)
offsprings <- df %>% group_by(offspring) %>% slice(1) %>% select(time, offspring)
combined <- full_join(offsprings, parents)
#rows where the names match for both parent and offspring
matchingrows <-which(combined$parent == combined$offspring)
#update the times
for (i in matchingrows){
row = which(df$time == combined$time[i] & df$offspring == combined$offspring[i])
df$time[row] <- df$time[row] - 0.5
}
df
推荐阅读
- ansible - Touch log file with Ansible only when it does not start with __
- ios - 已安装的应用程序灰显且无法打开
- javascript - 如何解决 math.js 中的未知数?
- java - 如何将 RadioGroup 验证为必填字段?
- wordpress - wp-admin 已经设置了 .htaccess 规则
- spring - "lateinit 属性
在 Kotlin 上使用带有 SpringBootTest 的 WebTestClient 时尚未初始化” - javascript - 我如何将 -tabulator excel- 对象发送到服务器端(node.js)?
- java - 在单个循环中查找具有最小平均值的整数数组中的子数组
- uwp - AppServiceConnection 重新构建已经运行的应用程序
- bash - 仅在特定条件下翻转两列(用于荟萃分析)