使用 tidygraph 从 children 传播值

Propagate value from children with tidygraph

我有一棵在属级别注释的树(即每片叶子都有一个名字),我想在 branches/edges 中传播叶子的颜色,只要 children 具有相同的颜色属,就像在这个情节中:

Source

我的树是 here(抱歉,dput 不起作用...)他看起来像这样:

library(ggraph)
library(tidygraph)
load("tree_v3")

TBL %>% activate(nodes) %>% as_tibble
# A tibble: 50 x 2
    leaf      Genus
   <lgl>     <fctr>
 1 FALSE         NA
 2  TRUE Klebsiella
 3  TRUE Klebsiella
 4 FALSE         NA
 5  TRUE Klebsiella
 6  TRUE Klebsiella
 7 FALSE         NA
 8 FALSE         NA
 9  TRUE Klebsiella
10 FALSE         NA
# ... with 40 more rows

我可以用这段代码打印树,但如您所见,边缘颜色保持在树叶附近。

TBL %>%
  ggraph('dendrogram') + 
  theme_bw() +
  geom_edge_diagonal2(aes(color = node.Genus)) +
  scale_edge_color_discrete(guide = FALSE) +
  geom_node_point(aes(filter = leaf, color = Genus), size = 2)

搜索映射 部分中有一个代码 blog post 但它对我的数据不起作用,我不明白为什么.. .

TBL2 <- TBL %>%
  activate(nodes) %>%
  mutate(Genus = map_bfs_back_chr(node_is_root(), .f = function(node, path, ...) {
    nodes <- .N()
    if (nodes$leaf[node]) return(nodes$Genus[node])
    if (anyNA(unlist(path$result))) return(NA_character_)
    path$result[[1]]
  }))

Error in mutate_impl(.data, dots) : Evaluation error: Cannot coerce values to character(1).

在 Marco Sandri 回答后进行编辑

使用 mutate(Genus = as.character(Genus)) 时,不再有错误消息,但 Genus 无法正确传播。例如,请看从右边开始的第三个和第四个节点:parent 应该是 NA...(请注意,它在博客 post 情节中也不起作用) .

GenusTBL是一个因数:

str(TBL %>% activate(nodes) %>% as_tibble)

# Classes ‘tbl_df’, ‘tbl’ and 'data.frame':       50 obs. of  2 variables:
# $ leaf : logi  FALSE TRUE TRUE FALSE TRUE TRUE ...
# $ Genus: Factor w/ 10 levels "","Citrobacter",..: NA 6 6 NA 6 6 NA NA 6 NA ...

但应该是一个字符。
Genus 从因子转换为字符后,代码有效。

TBL2 <- TBL %>%
  activate(nodes) %>% 
  mutate(Genus = as.character(Genus)) %>%
    mutate(Species = map_bfs_back_chr(node_is_root(), .f = function(node, path, ...) {
        nodes <- .N()
        if (nodes$leaf[node]) return(nodes$Genus[node])
        if (anyNA(unlist(path$result))) return(NA_character_)
        path$result[[1]]
    }))