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

时间:2020-01-13 22:59:05

标签: r recursion data-structures tidyverse graph-theory

我有一个数据集,对这样的单位之间的转换进行编码,其中单位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的答案,而不是使用诸如ig​​raph之类的图形库,这样我才能真正了解机械的变化。

1 个答案:

答案 0 :(得分:0)

这是一个可行的建议:

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)
}