Reputation: 595
I probably could have worded the title better, but I am wanting to collapse any clade within a phylogenetic tree (even if the clade has one member) which has a tip label of "foo" and then count the number of tips which were dropped from that specific clade and create a branch with a tip label displaying 35 foos.
The counting portion is easy; however, when I use
drop.tip(rooted.tree,tip=which(rooted.tree$tip.label=='foo'),subtree=TRUE)
the dropped tips do not maintain their position in the tree. Rather, they are all grouped at the end (counted properly however). Is there anyway to collapse a clade by tip labels and maintain its position on the tree?
Upvotes: 1
Views: 1268
Reputation: 7816
The tricky part is determining how many individual monophyletic clades you have. This function should do the trick.
collapse_identical_tips <- function(phy,tip_label){
matching_tips <- which(phy$tip.label==tip_label)
nt <- length(phy$tip.label) # number of tips in tree
nm <- length(matching_tips) # Number of tips matching the label
keep <- numeric(nm)
cur_tip <- 1
while(cur_tip<=nm){
if(cur_tip == nm){
keep[cur_tip] <- 1
break
}
next_tip <- cur_tip + 1
mrca_ <- getMRCA(phy,c(matching_tips[cur_tip],matching_tips[next_tip]))
descendants <- getDescendants(phy, mrca_)
descendant_tips <- descendants[descendants<=nt]
if(all(descendant_tips %in% matching_tips)){
keep[cur_tip] <- 1
cur_tip <- cur_tip + length(descendant_tips)
}else{
keep[cur_tip] <- 1
cur_tip <- cur_tip + 1
}
}
to_drop <- matching_tips[!keep]
new_phy <- drop.tip(phy,to_drop)
return(new_phy)
}
Testing it out:
tc <- "(A:3.135206161,(B:2.757615245,(((C:0.5796267872,((foo:0.1917981792,(foo:0.08246947568,foo:0.08246947568):0.1093287035):0.2328473818,(D:0.3107268924,E:0.3107268924):0.1139186686):0.1549812262):0.3387382152,F:0.9183650024):1.172666972,(((G:0.02437174382,H:0.02437174382):0.4727952475,foo:0.4971669913):0.8701228492,(foo:1.124632261,(foo:0.6503599778,foo:0.6503599778):0.4742722831):0.2426575797):0.7237421344):0.6665832698):0.3775909166);"
phy <- read.tree(textConnection(tc))
plot(phy)
plot(collapse_identical_tips(phy,"foo"))
Upvotes: 1