嗨,我很难让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)
})
答案 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)
})