how to run lm regression for every column in R

前端 未结 3 520
慢半拍i
慢半拍i 2020-12-22 08:31

I have data frame as:

df=data.frame(x=rnorm(100),y1=rnorm(100),y2=rnorm(100),y3=...)

I want to run a loop which regresses each column start

3条回答
  •  天涯浪人
    2020-12-22 09:08

    Your code looks fine except when you call i within lm, R will read i as a string, which you can't regress things against. Using get will allow you to pull the column corresponding to i.

    df=data.frame(x=rnorm(100),y1=rnorm(100),y2=rnorm(100),y3=rnorm(100))
    
    storage <- list()
    for(i in names(df)[-1]){
      storage[[i]] <- lm(get(i) ~ x, df)
    }
    

    I create an empty list storage, which I'm going to fill up with each iteration of the loop. It's just a personal preference but I'd also advise against how you've written your current loop:

     for(i in names(df[,-1])){
        model = lm(i~x, data=df)
    }
    

    You will overwrite model, thus returning only the last iteration results. I suggest you change it to a list, or a matrix where you can iteratively store results.

    Hope that helps

提交回复
热议问题