0

I am a beginner in R, so excuse my stupid question. I am running a nested loop and want to extract results for the outer and inner loop in a particular format. This is the code I am using -

Res2<-NULL
Res1<-NULL
for (k in 2:ncol(df1)){
  for (i in 2:ncol(df2)){
    model<-lm(df1[,k]~df2[,i], na.action=na.exclude, data=df2)
    Res1<-rbind(Res1, coef(summary(model))[2,])
     }
    Res2<-cbind(Res2, Res1)
   }

Here I am running a linear regression for a number of dependent (response) variables of df1 (from column 2 to the end) against a list of independent variables in df2 (from column 2 to the end). I want to row bind coefficients of the ith iteration into a list, let's call it "Res1", and then want to column bind the next subsequent lists for kth iteration. However, with this code, I get a long list of results where the outer loop also adds results in rows, but not in the column.

A simple layout of the final results file that I want to extract would be something like this - where results of ith iteration will be added in rows and results of kth iteration will be added in columns. Thank you.

            K1   ................>                K2  ................> 
           beta   Std. Er    t val   P            beta   Std. Er    t val   P
  i    [1,]
       [2,]
Rahman
  • 1
  • 1
    Can you post your data in a reproducible format? You probably don't need a for loop for this, let along a nested for loop. – Ben G Feb 25 '19 at 18:35
  • Thanks for responding. The "seizure" data can be used as a prototype. Although in my code, I used two separate datasets, it is not a necessity. So, from seizure data, say I where I want to run a regression for each of the y1, y2, y3, y4 variables (response variables) against each of trt, base, and age variables (predictors) in a separate model. – Rahman Feb 26 '19 at 22:03
  • So the models will look like - (1) y1 = b0 + b1*trt +e; (2) y1 = b0 + b1*age +e; (3) y3 = b0+b1*base+e and then models for y2, y3, y4. I want to extract b1 from all models for the outcome, y1 (here model 1-3) and add them in rows (b1 for trt, age, and base in rows). Then I want to extract respective b1 from all models for the outcome, y2 in the 1st, 2nd, and 3rd rows of column 2. And continue the same way for the outcome, y3, y4 to add results in column 3 and 4. Thank you. – Rahman Feb 26 '19 at 22:03
  • You need to post your data and make your question reproducible. Check this out: https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – Ben G Feb 27 '19 at 13:48

0 Answers0