在 R 中使用“~调用”和动态变量

Using "~ call" in R with dynamic variables

我目前正在使用 R 进行回归和分类。

因此我使用类似于 X ~ Y 的公式来预测 X。 我现在尝试在 for 循环中使用 function 来对波浪号 X 侧的不同值和 Y 侧的常数值进行多重预测。是这样的: X1 ~ Y X2 ~ Y X3 ~ Y

其中 X1、X2、X3 和 Y 都是数据列 (data$X1 <- a, data$X2 <- b, data$X3 <- c, data$Y) 如果这在某种程度上很重要

那么我怎样才能在 ~-表达式中动态 select 一个变量呢?我已经尝试过类似的方法,但它不起作用:

# referring to "iris" data set with columns (Sepal.Length, Sepal.Width, Petal.Length, Petal.Width, Species)

getFormula <- function(variable){
  variable ~ Sepal.Length + Sepal.Width + Species
}

petal.length.formula <- getFormula(Petal.Length)
petal.width.formula <- getFormula(Petal.Width)

我明白了:

petal.length.formula: variable ~ Sepal.Lenght + Sepal.Width + Species
petal.width.formula: variable ~ Sepal.Lenght + Sepal.Width + Species

但我想实现这个:

petal.length.formula: Petal.Length ~ Sepal.Lenght + Sepal.Width + Species
petal.width.formula: Petal.Width ~ Sepal.Lenght + Sepal.Width + Species

由于我在 Y 端有 40 多个变量,在 X 端有 10 个变量,手动输入每个公式真的很麻烦。 有人可以帮我解决这个问题吗?

我找不到类似的问题,因为我很难弄清楚我必须使用的关键字来查找相关内容。

如果可能的话,我宁愿不使用任何额外的库,因为我是 R 的新手,想先弄清楚 R 的基本机制。

Since english is not my first language, I hope you can understand my question and I am of course happy to explain further if needed. Thank you in advance for your time!

你可以试试这个,你需要传递一个字符给变量。这样就容易多了,如果你在 X 端有 10 个变量,你可以轻松地遍历它们:

getFormula <- function(variable){
  as.formula(paste(variable,"~ Sepal.Length + Sepal.Width + Species"))
}

petal.length.formula <- getFormula("Petal.Length")
petal.width.formula <- getFormula("Petal.Width")

lm(petal.length.formula,data=iris)
Call:
lm(formula = petal.length.formula, data = iris)

Coefficients:
      (Intercept)       Sepal.Length        Sepal.Width  Speciesversicolor  
         -1.63430            0.64631           -0.04058            2.17023  
 Speciesvirginica  
          3.04911 

您也可以按照@BenBolker 和@MrFlick 的建议尝试重新制定:

getFormula <- function(variable){
  reformulate(c("Sepal.Length","Sepal.Width","Species"), 
response = variable, intercept = TRUE)
}

lm(getFormula("Petal.Length"),data=iris)

Call:
lm(formula = getFormula("Petal.Length"), data = iris)

Coefficients:
      (Intercept)       Sepal.Length        Sepal.Width  Speciesversicolor  
         -1.63430            0.64631           -0.04058            2.17023  
 Speciesvirginica  
          3.04911