looping over multiPhylo: why does "1:length(trees)" work?

Viewed 144

I have a question about for-loops and lists/multiPhylo-objects. I've actually solved the issue at hand, but I don't understand why the solution I applied worked. I'd love to know why it worked so that I can understand things better.

goal: use a for-loop to apply a particular function to every tree in a multiPhylo object, write each tree to file.

The particular set of trees I'm looping over happen to be accessible publicly via GitHub, so you can have a look yourself if you'd like.

library(ape)

#reading in data
fn <- "https://github.com/D-PLACE/dplace-data/blob/master/phylogenies/gray_et_al2009/original/a400-m1pcv-time.trees.gz"

trees <- read.nexus(fn)

The particular function I want to apply is just ape::drop.tip(). I'm doing a prune in two stages, but for the sake of the reprex let's just say I want to drop one tip from each tree - "Sisingga". I would have imagined that code chunk (a) below would work, but it doesn't. Instead (b) works. Why?

tip_to_drop <- "Sisingga"

index <- 0 #starting a count to have something to name files with uniquely

#code chunk a

for(tree in trees){
  
  index <- index +1
  
  tree <- ape::drop.tip(tree, tip_to_drop)
  
  output_fn <- paste0("tree_",  index, ".txt") #making unique file name
  write.nexus(tree,file = output_fn )
}

index <- 0

#code chunk b

for(tree in 1:length(trees)){

index <- index +1

tree <- trees[[tree]]
tree <- ape::drop.tip(tree, tip_to_drop)

output_fn <- paste0("tree_",  index, ".txt")
write.nexus(tree,file = output_fn )
}

I'm happy that I've solved my problem, but I'm left a bit confused. Any light would be welcome.

p.s. the reason I thought chunk (a) would work is because it has in the past in a similar situation, but with another multiPhylo object. In that case it was https://cdstar.shh.mpg.de/bitstreams/EAEA0-D501-DBB8-65C4-0/tree_glottolog_newick.txt.

0 Answers
Related