在不同系列的线性模型中循环多个变量组合的问题

Problems with looping multiple combinations of variables in linear models for different series

我遇到了一个问题,我认为它很容易解决,但我无法找到它的答案。

我有一个 excel 文件,其中包含一定数量的列,其中包含流量系列(T1、T2)和某些自变量(V1、V2、V3),我必须为其构建所有可能的组合线性模型。我已经能够以缓慢的方式完成它,但是我被要求使用循环进行优化,这就是我正在努力的地方。

这是一个可重现的例子:

set.seed(1)
rep.example<-data.frame(V1=rnorm(25,15),V2=rnorm(25,5),V3=runif(25,0.4),T1=rnorm(25,12),T2=rnorm(25,35))

ind.vars = c("V1","V2","V3")

Comb.Matrix <- expand.grid(c(TRUE, FALSE), c(TRUE, FALSE), c(TRUE, FALSE))
names(Comb.Matrix) <- ind.vars

Comb.Matrix <- Comb.Matrix[-(dim(Comb.Matrix)[1]),]


allModelsList       <- apply(Comb.Matrix,
                             1,
                             function(x) as.formula(paste(c(" T1 ~ ",
                                                            ind.vars[x]), collapse = " + ")))

这将创建一个列表,其中包含交通系列 T1 的线性模型的所有可能组合。但是,我有一些数据,有时我可能有多个流量系列列,我希望模型遍历这些列,以便将所有组合存储在列表中。我尝试将以下内容添加到代码中:

Series <- c("T1", "T2")

for (i in 1:length(Series)){
  allModelsList <- apply(Comb.Matrix,
                         1,
                         function(x) as.formula(paste(c(Series[i]," ~ ",
                                                        ind.vars[x]), 
                                                      collapse = " + ")))
}

我希望它转到 Series 的每个值,并以“T1 ~ Var Combinations”的形式与该值进行所有可能的组合,对于 T2 和更多最终列也是如此....

提前致谢。

我通过执行以下操作设法解决了这个问题:

allModelsList=list()

for (i in 1:length(Series)){
  allModelsList <- append(
    allModelsList, 
    apply(Comb.Matrix, 1, function(x) as.formula(paste(c(paste(" ", Series[i], " ~ "), ind.vars[x]), collapse = " + ")))
  )
}

对于 "Series" 中的每个 index/column,模型执行所有可能的变量组合。