Created
May 7, 2012 19:28
-
-
Save hlapp/2629846 to your computer and use it in GitHub Desktop.
TreEvo for-loop optimization example 1: before and after
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## | |
# 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