R语言如何合并含公共元素的两个向量得到连续指向序列
R向量链式指向合并方案
场景说明
你现有两个长度为2的向量分别代表两段指向关系:
ord1 = c(1,2)对应指向1→2ord2 = c(3,1)对应指向3→1
需要合并得到完整链式序列3 1 2。
解法1:双向量场景简化版
如果确定只有两段指向关系、且仅存在一个公共交点,可以直接判断两段的首尾匹配关系,代码如下:
ord1 <- c(1,2) ord2 <- c(3,1) # 判断哪段的尾是另一段的头 if (ord2[2] == ord1[1]) { res <- c(ord2[1], ord1) } else if (ord1[2] == ord2[1]) { res <- c(ord1[1], ord2) } print(res) # 输出: 3 1 2
解法2:多段指向通用版
如果后续可能扩展到多段指向关系,可以通过邻接遍历的方式实现,兼容性更强:
# 所有指向关系存入列表 edges <- list(ord1, ord2) # 提取所有节点、被指向节点,找到入度为0的起点 all_nodes <- unique(unlist(edges)) to_nodes <- sapply(edges, \(x) x[2]) start_node <- all_nodes[!all_nodes %in% to_nodes] # 从起点开始遍历完整链路 res <- c() current <- start_node while (!is.na(current)) { res <- c(res, current) next_edge <- which(sapply(edges, \(x) x[1] == current)) current <- if (length(next_edge) > 0) edges[[next_edge]][2] else NA } print(res) # 输出: 3 1 2
内容的提问来源于stack exchange,提问作者Yasaman
相关产品推荐
相关产品推荐

