r对所选变量运行lm

时间:2016-05-16 04:50:18

标签: r lm

我有大约26个变量,我需要按如下方式运行分析:

model1=lm(var1~condition*time,data=main_df)

如何避免这样写26次并对变量1 - 26进行相同的分析?

2 个答案:

答案 0 :(得分:0)

以下是如何使用regsubsets导出不同的公式:

library(leaps)
data(swiss)
a <- regsubsets(Fertility ~., data=swiss, nbest=1000, method="exhaustive, intercept=F, really.big=T)
b <- summary(a)[[1]] # return matrix with different combinations
b[1:15, ]

  Agriculture Examination Education Catholic Infant.Mortality
1       FALSE       FALSE     FALSE    FALSE             TRUE
1        TRUE       FALSE     FALSE    FALSE            FALSE
1       FALSE        TRUE     FALSE    FALSE            FALSE
1       FALSE       FALSE     FALSE     TRUE            FALSE
1       FALSE       FALSE      TRUE    FALSE            FALSE
2       FALSE       FALSE      TRUE    FALSE             TRUE
2        TRUE       FALSE     FALSE    FALSE             TRUE
2       FALSE        TRUE     FALSE    FALSE             TRUE
2       FALSE       FALSE     FALSE     TRUE             TRUE
2        TRUE        TRUE     FALSE    FALSE            FALSE
2        TRUE       FALSE      TRUE    FALSE            FALSE
2       FALSE        TRUE     FALSE     TRUE            FALSE
2        TRUE       FALSE     FALSE     TRUE            FALSE
2       FALSE        TRUE      TRUE    FALSE            FALSE
2       FALSE       FALSE      TRUE     TRUE            FALSE

forms <-lapply(1:nrow(b), function(x)as.formula(paste("Fertility ~", paste(names(which(b[x,])), collapse="+"))))
head(forms)
[[1]]
Fertility ~ Infant.Mortality
<environment: 0x00000000199a6af0>

[[2]]
Fertility ~ Agriculture
<environment: 0x00000000199aa5c8>

[[3]]
Fertility ~ Examination
<environment: 0x00000000199ad140>

[[4]]
Fertility ~ Catholic
<environment: 0x00000000199afcb8>

[[5]]
Fertility ~ Education
<environment: 0x00000000199b3790>

[[6]]
Fertility ~ Education + Infant.Mortality
<environment: 0x00000000199b6308>

要包含互动因素,请先创建最不可能看的回归公式,然后在regsubsets中运行:

library(dplyr) # loading this to make use of select & magrittr pipes
pred <- swiss %>% select(Agriculture:Infant.Mortality)  %>% names
all.terms <- as.formula(paste("Fertility", paste(pred, collapse="*"), sep="~"))
mods<-regsubsets(all.terms, data=swiss, nbest=1000, method="exhaustive", intercept=F, really.big=T)
b <- summary(mods)[[1]] 
str(b)
 logi [1:6496, 1:31] FALSE FALSE TRUE FALSE FALSE FALSE ...
 - attr(*, "dimnames")=List of 2
  ..$ : chr [1:6496] "1" "1" "1" "1" ...
  ..$ : chr [1:31] "Agriculture" "Examination" "Education" "Catholic" ...
# i.e. 6496 combinations based on 31 variables based from 5 fixed factors and different interaction combinations

答案 1 :(得分:0)

我会使用一个列表存储所有的ouctomes以便于进一步操作(摘要,系数提取......) 需要尝试的东西:

lapply(as.list(1:26),FUN=function(i){lm(as.formula(paste("var",i,"~condition*time",sep="")),data=main_df)})