Skip to content

Instantly share code, notes, and snippets.

@dsparks
Created September 12, 2012 13:19
Show Gist options
  • Save dsparks/3706541 to your computer and use it in GitHub Desktop.
Save dsparks/3706541 to your computer and use it in GitHub Desktop.
lapply() as an alternative to a multiply-nested loop
# Alternative to a doubly-nested loop
# Imagine I want to perform an operation on a data frame
# once for each combination of two variables, such as Country and Year
# I can do this with a nested loop, or I can do this with (among other
# things) lapply()
# Generate random data:
allCountries <- LETTERS[1:10]
allYears <- 1990:2012
myData <- expand.grid(allCountries, allYears) # This is a useful function
colnames(myData) <- c("Country", "Year")
myData$variable1 <- rnorm(nrow(myData))
myData$variable2 <- rnorm(nrow(myData))
head(myData)
# Silly function to perform
myFunction <- function(x, y){
x * y - x / y
}
### Doubly-nested loop ###
myData$computedFigure <- NA # Make an "empty" variable in my data.frame
for(ii in allCountries){
for(jj in allYears){
tempX <- myData[myData$Country == ii & myData$Year == jj, c("variable1")]
tempY <- myData[myData$Country == ii & myData$Year == jj, c("variable2")]
# "Save" results into appropriate location in my data.frame
myData[myData$Country == ii & myData$Year == jj, c("computedFigure")] <- myFunction(tempX, tempY)
}
}
### Simple lapply() approach ###
computedFigureList <- lapply(1:nrow(myData), function(x){
tempX <- myData[x, c("variable1")]
tempY <- myData[x, c("variable2")]
# "Save" results into appropriate location in my data.frame
myFunction(tempX, tempY)
})
# This produces a list. Use unlist() here, to convert to a vector
# and add that vector to the data.frame
myData$computedFigure2 <- unlist(computedFigureList)
with(myData, plot(computedFigure, computedFigure2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment