Search code examples
rloopsframe

Loop to subtract columns of different data frames to normalize data


I need to subtract time zero absorbance column from four other data frames to normalize data. Ideally this will be done by a loop that goes through each data frame and subtracts each absorbance column from the original time zero absorbance creating a 4 new normalized data frames. I have a lot of data so a loop is the only feasible option. To give you an idea A data frame looks like:

well ID, Absorbance value


Solution

  • It is overall a bad idea to keep data of corresponding measurements within different data.frames. You should really consider putting all those measurements into one data.frame and then your task will become almost trivial. Please consider cbinding or mergeing your data.frames.

    Ok, back to the original question. Optimally you'd have all of the data.frames you want to loop over in a list as in

    expl <- list(
      one.hour = data.frame(id = 1:10, absorbance = runif(10)),
      two.hours = data.frame(id = 1:10, absorbance = runif(10)),
      three.hours = data.frame(id = 1:10, absorbance = runif(10))
    )
    
    zero.absorbance <- data.frame(id = 1:10, absorbance = runif(10))
    

    Then you can loop over the elements of that list e.g., with a for loop

    for (i in 1:length(expl)){
      expl[[i]]$corrected.absorbance <- expl[[i]]$absorbance - zero.absorbance$absorbance
    }
    

    And peak at the results:

    head(expl[[1]])  # first example data.frame
    head(expl[[2]])  # second example data.frame
    head(expl[[3]])  # third...