Skip to content

Instantly share code, notes, and snippets.

@hlapp
Created May 7, 2012 19:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hlapp/2629846 to your computer and use it in GitHub Desktop.
Save hlapp/2629846 to your computer and use it in GitHub Desktop.
TreEvo for-loop optimization example 1: before and after
##
# before for-loop optimization
##
getSimulationSplits<-function(phy) {
phy$node.label<-NULL
branchingTimes<-sort(branching.times(phy), decreasing=TRUE)
branchingTimesNames<-names(branchingTimes)
ancestorVector<-c()
descendant1Vector<-c()
descendant2Vector<-c()
for (i in 1:length(branchingTimes)) {
relationshipVector<-phy$edge[phy$edge[, 1]==branchingTimesNames[i]]
ancestorVector<-c(ancestorVector, relationshipVector[2])
descendant1Vector<-c(descendant1Vector, relationshipVector[3])
descendant2Vector<-c(descendant2Vector, relationshipVector[4])
}
return(data.frame(branchingTimes, ancestorVector, descendant1Vector, descendant2Vector))
}
##
# after converting for-loop into vector programming
##
getSimulationSplits<-function(phy) {
phy$node.label<-NULL
branchingTimes<-sort(branching.times(phy), decreasing=TRUE)
branchingTimesNames<-names(branchingTimes)
# To optimize away the for() loop without parallelization: The basic
# idea is that each iteration of the loop creates a vector of size
# 4, of which the last 3 elements get each appended to 3 different
# lists. Afterwards, the 3 lists get combined together to a
# datamatrix. Thus, if we can in one step create a matrix consisting
# of all these 4-element vectors, we can dispose of the for()
# loop. sapply() does just that:
m <- sapply(branchingTimesNames, function(i) phy$edge[phy$edge[,1]==i]);
# remove the first element (only the last 3 are needed), then transpose
m <- t(m[-1,])
# compose the dataframe (the naming of the columns may need to be corrected)
return(data.frame(cbind(branchingTimes, m)));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment