具有动态变量数的公式

时间:2011-02-09 22:42:39

标签: r formula

假设有一些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?)
   }
}

5 个答案:

答案 0 :(得分:84)

?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

答案 1 :(得分:52)

遗忘的功能是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

答案 2 :(得分:11)

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

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

lm(Y ~ foo[,factors])

答案 3 :(得分:3)

您实际上并不需要公式。这有效:

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

就像这样:

v <- c("Y", "factor1", "factor2")
do.call("lm", list(bquote(data_frame[.(v)])))

答案 4 :(得分:0)

我通常会通过更改响应列的名称来解决此问题。动态更容易,也可能更干净。

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, ...)