r遍历data.frame以使用不同的DV和权重运行相同的回归

时间:2019-03-09 18:18:01

标签: r lm

嗨,我很难让lm进入不同的DV循环中,为此我已经在data.frame中预先确定了相应的权重列。

这是一个可行的示例:

require(dplyr)


df <- mtcars %>% mutate_at(
  vars(mpg:drat),
  funs(wt=rnorm(n()))
  )
dvs <- names(select(df,mpg:drat))
res <- list()
res <- lapply(dvs, function(x) {
  formula <- as.formula(paste0(x," ~ wt + qsec + as.factor(vs)"))
  lm(formula,df)
})

但这将返回“找不到对象'mpg_wt'”

res <- lapply(dvs, function(x) {
  formula <- as.formula(paste0(x," ~ wt + qsec + as.factor(vs)"))
  weightvars <- paste0(x,"_wt")
  lm(formula,weights=as.formula(weightvars),df)
})

并返回“可变长度不同(找到'(weights)')”

res <- lapply(dvs, function(x) {
  formula <- as.formula(paste0(x," ~ wt + qsec + as.factor(vs)"))
  weightvars <- paste0(x,"_wt")
  lm(formula,weights=eval(weightvars),df)
})

1 个答案:

答案 0 :(得分:1)

只需使用解析并将weightvars传递为text的值即可。

我希望这会有所帮助:


res <- lapply(dvs, function(x) {
  formula <- as.formula(paste0(x," ~ wt + qsec + as.factor(vs)"))
  weightvars <- paste0(x,"_wt")
  lm(formula,weights=eval(parse(text=weightvars)),df)
})

或在as.name内使用eval函数,如下所示:

res <- lapply(dvs, function(x) {
  formula <- as.formula(paste0(x," ~ wt + qsec + as.factor(vs)"))
  weightvars <- paste0(x,"_wt")
  lm(formula,weights=eval(as.name(weightvars)),data=df)
})