2

I have a list of 33 dataframes (each dataframe has a different number of rows). I am trying to write a nested for loop that will go through each dataframe in the list, and then go through each row within that dataframe and apply a function, before coming out again and moving onto the next dataframe in the list. However, Im not sure how to index a specific row within a dataframe within a list. If anyone knows how to do this or a more efficient way of doing this it would be much appreciated. Thanks.

for (i in 1:length(data.list)) {
  #Creating a matrix of all possible combinations of pairs in order to do pairwise comparisons on all of the sites
  pairs = t(combn(nrow(data.list[[i]]), m = 2))
  #Some more data wrangling
  pairs <- as.data.frame(pairs)
  colnames(pairs) <- c("PaperOneRowNumber", "PaperTwoRowNumber")
  pairs$LRR <- 0
  pairs$LRR_var <- 0

  for (j in 1:nrow(pairs)) {
    #print(i)
    #Assigning Paper IDs to variables
    a <- pairs[j,1]
    b <- pairs[j,2]
    #print(a)
    #print(b)
    paperone <- data.list[[i[a,]]]
    papertwo <- data.list[[i[b,]]]
    #print(paperone)
    #print(papertwo)

    #Inputting variables into calc.effect function and saving the output
    effect.size <- calc.effect(paperone, papertwo)
    #print(effect.size)
    pairs$LRR[j] <- effect.size$LRR
    pairs$LRR_var[j] <- effect.size$LRR_var
  }
}
  • Write a function (that takes a `data.frame` as its first/only parameter) and which produces the result you want for a single `data.frame`. Call this function `myFunc`. Then `lapply(data.list, myFunc)` returns a list of the required results. Each entry in the list contains the result for the corresponding `data.frame`. Without test data to work on, it's difficult to be more precise. Your sample code is, err... , convoluted. – Limey Aug 09 '22 at 11:06
  • In your code, `data.list[[i[a,]]]` will fail because `i` is a scalar, not a list or a data frame. To get the ith element of `data.list` write `data.list[[i]]`. You can then access rows/columns within that individual data.frame with, say, `data.list[[i]][a,]`. But I'm not sure if that's what you want to do because I'm confused by what you are attempting to do. – Limey Aug 09 '22 at 11:10
  • check https://stackoverflow.com/a/5963379/5224236 – gaut Aug 09 '22 at 11:15

0 Answers0