将条件应用于向量的多个元素?警告消息:条件的长度 > 1,将仅使用第一个元素

Apply condition to multiple elements of a vector? Warning message: the condition has length > 1 and only the first element will be used

我正在 运行 建立一堆回归模型,筛选混杂的协变量,并编写了一个函数来简化过程,如果协变量是混杂因素,则仅在控制台上显示回归结果。下面是一些随机的样本数据来说明这个想法:

Var1 <- c(2.3940, 4.3848, 4.2840, 5.37393, 19.383948)
Var2 <- c(383, 4840, 38404, 48403, 8302)
data <- data.frame(Var1, Var2)
attach(data)

我的协变量之一是具有三个水平的因子变量:

Var3 <- c(3938, 48403, 585038, 383028, 474937)
Var4 <- c(.373938, .473038, .830937, .3830938, 1.203)
Var5 <- as.factor(c("Ever", "Sometimes", "Never", "Sometimes", "Ever"))
Covariates <- data.frame(Var3, Var4, Var5)

以及函数:

confounder <- function(model) {
  model.sum <- summary(model)
  model.b <- model.sum$coefficients[2, 1]
  oldmodel <- update(model, . ~ . - x)
  oldmodel.sum <- summary(oldmodel)
  oldmodel.b <- oldmodel.sum$coefficients[2, 1]
  model.frame <- tidy(model)
  newvar.b <- model.frame[grep("x", model.frame$term), 5]
  if (abs(model.b - oldmodel.b)/abs(model.b) >= .1 | newvar.b < .05) {
    return(model.sum)
  }
}

然后我 运行 使用 lapply:

lapply(Covariates, function(x) {
  confounder(lm(Var1 ~ Var2 + x))
})

我收到此错误消息:

Warning messages:
1: In if (abs(model.b - oldmodel.b)/abs(model.b) >= 0.1 | newvar.b <  :
  the condition has length > 1 and only the first element will be used
2: In if (abs(model.b - oldmodel.b)/abs(model.b) >= 0.1 | newvar.b <  :
  the condition has length > 1 and only the first element will be used

当我得到一个具有多个水平的因子变量时,如何更改此函数以应用条件?本质上,如果因子变量的任何水平符合条件,而不仅仅是第一个水平,我希望控制台显示回归输出。希望这是有道理的。

谢谢!

在您的 if 语句中使用 any() 函数:

confounder <- function(model) {
  model.sum <- summary(model)
  model.b <- model.sum$coefficients[2, 1]
  oldmodel <- update(model, . ~ . - x)
  oldmodel.sum <- summary(oldmodel)
  oldmodel.b <- oldmodel.sum$coefficients[2, 1]
  model.frame <- tidy(model)
  newvar.b <- model.frame[grep("x", model.frame$term), 5]
  if (any(abs(model.b - oldmodel.b)/abs(model.b) >= .1 | newvar.b < .05)) {
    return(model.sum)
  }
}