Search code examples
listdataframefor-loopregressionnested-loops

How to do a loop over a colnames of data frames stored in a list in r


I'm seeking to conduct a beta regression across columns of multiple data frames stored on a list. The data frames stored in the list are from two data frames, one containing dependent factors and another containing independent variables (environmental). Subsequently, I pasted a column to environmental data frames acquired from multiple tables to carry out the regression.

Environmental data frame

Ev = data.frame(a = runif(20,1,999), b = runif(20,1,7000), c = runif(20,1,3000), d = runif(20, 1, 250)))

Biotic index data frame

Index = data.frame(Pielou = runif(20,0,1), Simpson = runif(20,0,1), LCBD = runif(20, 0, 1), Q = runif(20, 0, 0.8), D = runif(20,0,0.6))

Here I pasted each Bio column in environmental df.

LT = list()
for(i in seq_along(Index)){
LT[[i]] = data.frame(Index[,i], Ev)
}

Then, I performed the regression.

Ldf1 = list();LBM1 = list()
for(i in seq_along(LT)){
LBM1[[i]] = betareg(LT[[i]][[1]] ~ LT[[i]][[i+1]])
Ldf1[[i]] = summary(LBM[[i]])
}

However, the loop only provided me with four results of the first data frame.

results of two of the 4 summaries


Solution

  • I hope this works for you.

    Ldf1 = vector("list", length(LT) * length(Ev))
    LBM1 = vector("list", length(LT) * length(Ev))
    idx = 1
    for(i in seq_along(LT)){
      for(j in seq_along(Ev)){
        LBM1[[idx]] = betareg(LT[[i]][[1]] ~ LT[[i]][[j]])
        Ldf1[[idx]] = summary(LBM1[[idx]]) 
        idx = idx+1
      }
    }