Skip to content

Instantly share code, notes, and snippets.

@Balharbi
Forked from dsparks/Avoiding a loop.R
Created June 28, 2020 01:44
Show Gist options
  • Select an option

  • Save Balharbi/54f8da6a0e9764de6b0a3b4c0b3d554d to your computer and use it in GitHub Desktop.

Select an option

Save Balharbi/54f8da6a0e9764de6b0a3b4c0b3d554d to your computer and use it in GitHub Desktop.

Revisions

  1. @dsparks dsparks revised this gist Sep 12, 2012. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion Avoiding a loop.R
    Original file line number Diff line number Diff line change
    @@ -33,7 +33,7 @@ for(ii in allCountries){
    }
    }

    ### simply lapply() approach ###
    ### Simple lapply() approach ###

    computedFigureList <- lapply(1:nrow(myData), function(x){
    tempX <- myData[x, c("variable1")]
  2. @dsparks dsparks created this gist Sep 12, 2012.
    49 changes: 49 additions & 0 deletions Avoiding a loop.R
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,49 @@
    # 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)
    }
    }

    ### simply 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))