I have a tree and I want to get part of the tree that is ancestors of cutree groups.
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)
I am using cutree
to get a certain number of groups:
cutree(as.hclust(tree), k = 3)
run2 run7 run8 run14 run9 run6
1 1 2 2 3 3
How to get the left part of tree? Essentially this 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)
You can use the function ape::drop.tip
using the trim.internal = FALSE
option:
## Dropping all the tips and their edges leading to the nodes (internals)
tree2 <- drop.tip(tree, tip = tree$tip.label, trim.internal = FALSE)
Of course, should you need, you can also specify to drop only a certain number following your hclust::cutree
function results:
## 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)
If you want to also remove nodes as well as tips (say removing all tips AND nodes "master6"
and "master5"
you can pass that tree to the same drop.tip
function again:
## 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)