繁体   English   中英

在 R 中查找沿该路径的所有节点的路径终点

[英]Find end point of path for all nodes along that path in R

我有一个数据集,可以对这样的单元之间的转换进行编码,其中单元 A 是在特定日期取代单元 B 的单元。 在单元 A 取代单元 B 之后,它现在是活动单元。

Unit A | Transition Date | Unit B
---------------------------------
xxx04  | 1/1/2020        | xxx03
xxx03  | 15/7/2019       | xxx02
xxx02  | 12/6/2005       | xxx01
aaa02  | 19/6/2015       | aaa01
bbb03  | 23/5/2010       | bbb02
bbb02  | 1/4/2009        | bbb01

实际数据集有大约 30,000 个转换,在 1 个转换和 30 个之间变化。

我想知道的是对于数据集中的每个单元(单元 A 和单元 B),如果它是单元链的一部分,那么链中的最终单元是什么。 所以我想最终的数据集应该是这样的:

Unit  | Final Unit
------------------
xxx01 | xxx04
xxx02 | xxx04
xxx03 | xxx04
xxx04 | xxx04
aaa01 | aaa02
aaa02 | aaa02
bbb01 | bbb03
bbb02 | bbb03
bbb03 | bbb03

基于我的谷歌搜索,我认为这是一个图形问题,我需要对节点之间的路径进行编码并找到路径上的最终节点。 但我不确定如何在 R 中实际编写代码来做到这一点。 我认为它将涉及一个循环遍历项目的递归函数。

理想情况下,我会喜欢基本 R/tidyverse 中的答案,而不是使用一些图形库(例如 igraph),这样我才能真正理解机械上发生的事情。

这是一个可能有效的建议:

library(tidyverse)

df <- tibble(unit_a = c("x4", "x3", "x2", "a2", "b3", "b2"), 
             unit_b = c("x3", "x2", "x1", "a1", "b2", "b1"))


# get all units and identify non final units:
all_units <- unique(c(df$unit_a, df$unit_b))
non_final_units <- all_units[all_units %in% df$unit_b] ## assumption: none of the final units appear in df$unit_b

# initial result mapping
mapping <- tibble(unit = all_units, final_unit = all_units)

#get the indices of non-final units in mapping$final_units, i.e. those which need replacement
repl <- which(mapping$final_unit %in% non_final_units)

while (length(repl) > 0) # as long as there are still non-final elements in mapping$final_unit
{ 
    # build vector with elements to be replaced:
    repl_v <- sapply(repl, function(x) df$unit_a[df$unit_b == mapping$final_unit[x]])

    # replace non-final elements
    mapping$final_unit[repl] <- repl_v

    # get the indices of still non-final units:
    repl <- which(mapping$final_unit %in% non_final_units)
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM