首页 > 解决方案 > 根据其他两列的值更改 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))

我想要帮助的是

  1. 找到存在于一个时间点但不存在于前一个时间点的所有后代(不考虑时间点 0),并像 D 和 F 一样作为后代和父亲

  2. 当我找到它们时,我想将一个确切的时间点减少 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

对此问题的任何帮助或指导将不胜感激。

标签: rdataframedplyrtidyverse

解决方案


创建 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

推荐阅读