【问题标题】:Apply condition to multiple elements of a vector? Warning message: the condition has length > 1 and only the first element will be used将条件应用于向量的多个元素?警告消息:条件的长度 > 1,并且只使用第一个元素
【发布时间】:2017-10-05 05:00:34
【问题描述】:

我正在运行一堆回归模型,筛选协变量以排除混杂因素,并编写了一个函数,仅当协变量是混杂因素时才在控制台上显示回归结果,从而简化流程。下面是一些随机的示例数据来说明这个想法:

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

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

谢谢!

【问题讨论】:

  • 好问题...请包括所有library 行,因为tidy() 不是基本R。
  • 另外,使用attach 是非常不可取的。您通常可以使用with 替换它。许多函数(如lmglmplot)都有一个数据参数,这也将否定attach 的需要。

标签: r function conditional


【解决方案1】:

在 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)
  }
}

【讨论】:

  • 谢谢!我不知道任何功能,但似乎将它添加到工具包中会非常有用。
猜你喜欢
  • 2020-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多