-
-
Save Balharbi/54f8da6a0e9764de6b0a3b4c0b3d554d to your computer and use it in GitHub Desktop.
lapply() as an alternative to a multiply-nested loop
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
# 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