1

我有一棵树,我想得到树的一部分,它是cutree 组的祖先。

library(stats)
library(ape)
tree <- ape::read.tree(text = "((run2:1.2,run7:1.2)master3:1.5,((run8:1.1,run14:1.1)master5:0.2,(run9:1.0,run6:1.0)master6:0.3)master4:1.4)master2;")
plot(tree, show.node.label = TRUE)

全树

cutree用来获取一定数量的组:

cutree(as.hclust(tree), k = 3)
 run2  run7  run8 run14  run9  run6 
    1     1     2     2     3     3 

如何获得树的左边部分?本质上是这样的tree2

tree2 <- ape::read.tree(text = "(master3:1.5,(master5:0.2,master6:0.3)master4:1.4)master2;")
plot(tree2, show.node.label = TRUE)

祖先树

4

2 回答 2

1

您可以使用ape::drop.tip以下trim.internal = FALSE选项使用该功能:

## Dropping all the tips and their edges leading to the nodes (internals)
tree2 <- drop.tip(tree, tip = tree$tip.label, trim.internal = FALSE)

当然,如果你需要,你也可以指定在你的hclust::cutree函数结果之后只删除某个数字:

## Dropping the tips and their edges that have a cut value equal to the scalar k
k = 3
tips_to_drop <- names(which(cutree(as.hclust(tree), k = k) == k))
tree3 <- drop.tip(tree, tip = tips_to_drop, trim.internal = FALSE)

如果您还想删除节点和提示(比如删除所有提示和节点"master6""master5"您可以再次将该树传递给相同的drop.tip函数:

## Removing master6 and master5 from the tree2
tree3 <- drop.tip(tree2, tip = c("master5", "master6"), trim.internal = FALSE)

## Or the same but with nested functions
tips_to_drop <- tree$tip.label
nodes_to_drop <- c("master5", "master6")
tree3 <- drop.tip(drop.tip(tree, tip = tips_to_drop, trim.internal = FALSE),
tip = nodes_to_drop, trim.internal = FALSE)
于 2021-03-02T10:54:10.580 回答
0

phangorn 包有一个 Ancestors 函数,但只会返回列表结构中的索引,而不是树结构中的标签。所以我为你标记了它们(检查了图表以确保标记的索引是正确的),但我会让你把它变成一棵树。

library(phangorn)
tree.labels <- c(tree$tip.label, tree$node.label)
tree.ancestors <- Ancestors(tree)
names(tree.ancestors) <- tree.labels
tree.ancestors.labelled <- lapply(tree.ancestors, function(ind.vec) tree.labels[ind.vec])

tree.ancestors.labelled
$run2
[1] "master3" "master2"

$run7
[1] "master3" "master2"

$run8
[1] "master5" "master4" "master2"

$run14
[1] "master5" "master4" "master2"

$run9
[1] "master6" "master4" "master2"

$run6
[1] "master6" "master4" "master2"

$master2
character(0)

$master3
[1] "master2"

$master4
[1] "master2"

$master5
[1] "master4" "master2"

$master6
[1] "master4" "master2"
于 2021-02-23T15:38:14.477 回答