更新时间:2023-11-25 21:00:10
这是使用 combn
函数获取所有变量组合的一种方法.它有点乱,并且使用了一个循环(也许有人可以使用 mapply
对此进行改进):
Here's one way to get all of the combinations of variables using the combn
function. It's a bit messy, and uses a loop (perhaps someone can improve on this with mapply
):
vars <- c("price","model","size","year","color")
N <- list(1,2,3,4)
COMB <- sapply(N, function(m) combn(x=vars[2:5], m))
COMB2 <- list()
k=0
for(i in seq(COMB)){
tmp <- COMB[[i]]
for(j in seq(ncol(tmp))){
k <- k + 1
COMB2[[k]] <- formula(paste("price", "~", paste(tmp[,j], collapse=" + ")))
}
}
然后,您可以调用这些公式并使用 list
存储模型对象,或者可能使用 assign
函数给出唯一名称:
Then, you can call these formulas and store the model objects using a list
or possibly give unique names with the assign
function:
res <- vector(mode="list", length(COMB2))
for(i in seq(COMB2)){
res[[i]] <- lm(COMB2[[i]], data=data)
}