Run linear models by group over list of variables in R

后端 未结 2 1082
太阳男子
太阳男子 2021-01-25 06:00

I have a data frame and I need to run 6 2-variable linear models for each group \'site\'. Then, I need to convert the results to a data frame. The second variable in the linear

2条回答
  •  青春惊慌失措
    2021-01-25 06:19

    I am not sure if this is exactly what you are trying to do, but the data.table plyr package allows you to run models split by multiple variables. Below is an example, with var1 and var2 simply representing two variables you want each combination of values to be modeled separately.

    #load packages
    library(data.table)
    library(plyr)
    
    #break up by variables, then fit the model to each piece
    models <- dlply(data, c("var1","var2"),
                  function(data)
                    lm(DV ~ 
                         IV1 + IV2
                       , data = data, weights = weights))
    #apply coef to eah model and return a df
    models_coef <- ldply(models, coef)
    #print summary
    l_ply(models_coef, summary, .print = T)
    

提交回复
热议问题