87

假设有一些 data.frame foo_data_frame并且想要通过其他一些列找到目标列Y的回归。为此,通常会使用一些公式和模型。例如:

linear_model <- lm(Y ~ FACTOR_NAME_1 + FACTOR_NAME_2, foo_data_frame)

如果公式是静态编码的,那效果很好。如果希望使用恒定数量的因变量(例如,2)来根植多个模型,则可以这样处理:

for (i in seq_len(factor_number)) {
  for (j in seq(i + 1, factor_number)) {
    linear_model <- lm(Y ~ F1 + F2, list(Y=foo_data_frame$Y,
                                         F1=foo_data_frame[[i]],
                                         F2=foo_data_frame[[j]]))
    # linear_model further analyzing...
  }
}

我的问题是当变量的数量在程序运行期间动态变化时如何做同样的影响?

for (number_of_factors in seq_len(5)) {
   # Then root over subsets with #number_of_factors cardinality.
   for (factors_subset in all_subsets_with_fixed_cardinality) {
     # Here I want to fit model with factors from factors_subset.
     linear_model <- lm(Does R provide smth to write here?)
   }
}
4

5 回答 5

110

参见?as.formula,例如:

factors <- c("factor1", "factor2")
as.formula(paste("y~", paste(factors, collapse="+")))
# y ~ factor1 + factor2

其中factors是包含要在模型中使用的因子名称的字符向量。您可以将其粘贴到lm模型中,例如:

set.seed(0)
y <- rnorm(100)
factor1 <- rep(1:2, each=50)
factor2 <- rep(3:4, 50)
lm(as.formula(paste("y~", paste(factors, collapse="+"))))

# Call:
# lm(formula = as.formula(paste("y~", paste(factors, collapse = "+"))))

# Coefficients:
# (Intercept)      factor1      factor2  
#    0.542471    -0.002525    -0.147433
于 2011-02-09T22:52:53.340 回答
70

一个经常被遗忘的功能是reformulate. 来自?reformulate

reformulate从字符向量创建公式。


一个简单的例子:

listoffactors <- c("factor1","factor2")
reformulate(termlabels = listoffactors, response = 'y')

将产生这个公式:

y ~ factor1 + factor2


虽然没有明确记录,但您也可以添加交互术语:

listofintfactors <- c("(factor3","factor4)^2")
reformulate(termlabels = c(listoffactors, listofintfactors), 
    response = 'y')

将产生:

y ~ factor1 + factor2 + (factor3 + factor4)^2

于 2012-11-14T00:50:47.623 回答
11

另一种选择可能是在公式中使用矩阵:

Y = rnorm(10)
foo = matrix(rnorm(100),10,10)
factors=c(1,5,8)

lm(Y ~ foo[,factors])
于 2011-02-09T23:25:49.330 回答
4

你实际上并不需要一个公式。这有效:

lm(data_frame[c("Y", "factor1", "factor2")])

就像这样:

v <- c("Y", "factor1", "factor2")
do.call("lm", list(bquote(data_frame[.(v)])))
于 2011-02-10T00:30:08.197 回答
1

我通常通过更改我的响应列的名称来解决这个问题。动态地做起来更容易,而且可能更干净。

model_response <- "response_field_name"
setnames(model_data_train, c(model_response), "response") #if using data.table
model_gbm <- gbm(response ~ ., data=model_data_train, ...)
于 2016-11-22T17:30:39.413 回答