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

时间:2018-04-04 11:44:18

标签: r recursion

我正在努力使用递归函数,其目标是确定哪些原材料属于哪种产品。我不知道如何处理数据框“db”中的多个可能路径。想要的功能应该给出:DB的A-B-C-E,A-B-C-F,A-B-D-F。我的功能适用于“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

Thx&amp;亲切的问候

1 个答案:

答案 0 :(得分:2)

这是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)

resulting plot

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