R 用于检查所有可能路径(从原材料到产品)的递归函数

R 用于检查所有可能路径(从原材料到产品)的递归函数,r,recursion,R,Recursion,我正在努力使用递归函数,其目标是确定哪些原材料属于哪个产品。我不知道如何处理数据帧“db”中的多个可能路径。想要的函数应该给出:A-B-C-E,A-B-C-F,A-B-D-F代表db。我的函数为“da”工作。我添加它是为了显示我所追求的,它有点像物料清单爆炸,但并不完全如此 da <- data.frame(parent = c("A", "B", "B", "C", "D"), child = c("B", "C", "D", "E", "F"),

我正在努力使用递归函数,其目标是确定哪些原材料属于哪个产品。我不知道如何处理数据帧“db”中的多个可能路径。想要的函数应该给出:A-B-C-E,A-B-C-F,A-B-D-F代表db。我的函数为“da”工作。我添加它是为了显示我所追求的,它有点像物料清单爆炸,但并不完全如此

da <- data.frame(parent = c("A", "B", "B", "C", "D"),
                 child = c("B", "C", "D", "E", "F"),
                 stringsAsFactors = FALSE)
db <- data.frame(parent = c("A", "B", "B", "C", "D", "C"),
                 child = c("B", "C", "D", "E", "F", "F"),
                 stringsAsFactors = FALSE)

my_path <- function(a, df) {
  b <- df$parent[df$child == a]
  if (length(b) == 0) {
    return(a)
  } else {
    return(c(my_path(b, df), a))
  }
}
end_points <- da$child[is.na(match(da$child, da$parent))]
lapply(end_points, function(x) my_path(x, da)) # -> ok
end_points <- db$child[is.na(match(db$child, db$parent))]
lapply(end_points, function(x) my_path(x, db)) # -> not ok

da这是igraph的工作:

#the data
db <- data.frame(parent = c("A", "B", "B", "C", "D", "C"),
                 child = c("B", "C", "D", "E", "F", "F"),
                 stringsAsFactors = FALSE)

#create a graph
library(igraph)
g <- graph_from_data_frame(db)

#plot the graph
plot(g)
#数据

db这很有帮助,但是如果我不知道“a”是起点,那么有可能在所有的路径中避免使用起点参数吗?(简单地从中删除不起作用)。您是否阅读了上面我定义期末考试的第二条评论?谢谢。找到了<代码>开始
#find all vertices that have no ingoing resp. outgoing edges
starts <- V(g)[degree(g, mode = "in") == 0] 
finals <- V(g)[degree(g, mode = "out") == 0]

#find paths, you need to loop if starts is longer than 1
res <- all_simple_paths(g, from = starts[[1]], to = finals)
#[[1]]
#+ 4/6 vertices, named, from 4b85bd1:
#[1] A B C E
#
#[[2]]
#+ 4/6 vertices, named, from 4b85bd1:
#[1] A B C F
#
#[[3]]
#+ 4/6 vertices, named, from 4b85bd1:
#[1] A B D F

#coerce to vectors
lapply(res, as_ids)