Home > Mobile >  loop regression columns r
loop regression columns r

Time:04-13

I have a dataframe like this one

ID  matching_var    status  code1   code2
 1  1                0       1      0
 2  1                1       1      0
 3  2                0       0      1

I have several other columns like code1 and code2, up to code25 and I would like to do these regressions:

fit1<-clogit(status~code1 strata(matching_variable),data=df)

fit2<-clogit(status~code2 strata(matching_variable),data=df)

fit25<-clogit(status~code25 strata(matching_variable),data=df

My variables code 1 to code25 are in columns 4 to 29 of my df

I would like to find a way to automate this without having to type in each regression model, and I would like to have all the regression results in one table

I have tried this:

regression <- function(x){code<- x[,4:29]
 f <- as.formula(
paste("status ~", code, "  strata(matching_var)"))
 clogit(f, data = x)
 }

result_reg<-lapply(df,regression)


lapply(result_reg, summary)

But it doesn't work, several other posts deal with the same subject but I haven't managed to find a solution to my problem...

Thanks in advance for the help

CodePudding user response:

Try this. I used the mtcars dataset since you did not post your data. Furthermore, explicitly call library when you use non-common function like clogit

 df <- mtcars
    library(survival)
    regression <- function(column){
      f <- as.formula(
      paste("vs ~", column, "  strata(carb)"))
    survival::clogit(f, data = df)
    }
    
    result_reg<-lapply(colnames(df)[9:11],regression)
    lapply(result_reg, summary)
  • Related