Regression by group

Just a very quick question, I want to run a regression using MASS. The dependent variable is val1, val2, val3, respectively, and the independent variables are a, b, c, d.

Just look at the fake data.

library(data.table)
library(MASS)
test <- data.table(val1 = 1:10, val2 = 11:20, val3 = 21:30, a = rnorm(10), b = rnorm(10), c = rnorm(10), d = rnorm(10))
summary1 <- glm.nb(val1 ~ a + b + c + d, data = test)
summary2 <- glm.nb(val2 ~ a + b + c + d, data = test)
summary3 <- glm.nb(val3 ~ a + b + c + d, data = test)

I think the code is ugly. I tried this

for (i in c("val1", "val2", "val3")){
paste("sum_", c("val1", "val2", "val3"), sep = "") <- glm.nb(i ~ a + b + c + d, data = simple)
}

But that did not work. Any suggestions for improvements? There are about 26 independent variables in the source data, and I think it will be uglier if the code looks like thissum1 <- glm.nb(val3 ~ a + b + c + d + e + f+ g + h + i + j + k + l, data = test)

I know that the following code may be useful, but I do not know how to use them ... :(

diff <- setdiff(colnames(test),c('val1','val2','val3'))

Also, I wonder if the lapply function can achieve this in data.table?

Thanks a lot!

+4
source share
3 answers

:

library(plyr)
library(reshape2)
xx <- melt(test,measure.vars=paste0('val',1:3))
ddply(xx,.(variable),function(x){
  coef(glm.nb(value~.,data=subset(x,select=-variable)))
})

 variable (Intercept)            a            b           c          d
1     val1    1.583602 -0.045909060 -0.018189342 0.026293033 0.29708648
2     val2    2.704601 -0.014641683 -0.003836401 0.006711503 0.10445377
3     val3    3.217729 -0.008925782 -0.001863267 0.003475509 0.06292286

, :

dlply(xx,.(variable),function(x){
  glm.nb(value~.,data=subset(x,select=-variable))
})
+5

, ,

results <- list()

for (i in c("val1", "val2", "val3")){
  frml <- paste(i, "~ a + b + c + d")
  frml <- as.formula(frml)

  results[[i]] <- glm.nb(frml, data = simple)
}

, results$val1 ..

+2

And here is the solution with lapply:

summary.list<-lapply(test[,grep('val',names(test)),with=FALSE],
                     function(i) glm.nb(i ~ a + b + c + d, data = test))
+1
source

All Articles