R:从 with.mids() 中的字符串构建公式
R: Building formulas from strings in with.mids()
我希望能够 运行 基于从字符串构造的公式对 mice()
返回的 mids
对象进行回归。对于普通回归(没有插补),这很容易:
library(mice)
for (x in c('age','hyp','chl')) {
regx <- lm(data=nhanes2,paste('bmi ~',x))
print(summary(regx)$coefficients)
}
我认为在估算数据集上做同样的事情应该是这样的:
imp <- mice(nhanes2,printFlag = FALSE)
for (x in c('age','hyp','chl')) {
regx <- with(data=imp,exp=lm(paste('bmi ~',x)))
summary(pool(regx))
}
然而,R 告诉我 object 'bmi' was not found
.
reg <- with(data=imp,exp=lm(bmi ~ age))
summary(pool(reg))
工作正常,但要求我对列名进行硬编码而不是提供字符串变量。
有办法吗?
通常 lm
接受字符串代替公式,但它似乎不在 with.mids
之内,因此请自行将其转换为公式:
f <- function(nm) {
s <- paste("bmi", nm, sep = "~")
regx <- with(imp, lm(as.formula(s)))
summary(pool(regx))
}
Map(f, names(nhanes)[-2])
注意:您可能希望将此报告给 mice 软件包维护者。
我希望能够 运行 基于从字符串构造的公式对 mice()
返回的 mids
对象进行回归。对于普通回归(没有插补),这很容易:
library(mice)
for (x in c('age','hyp','chl')) {
regx <- lm(data=nhanes2,paste('bmi ~',x))
print(summary(regx)$coefficients)
}
我认为在估算数据集上做同样的事情应该是这样的:
imp <- mice(nhanes2,printFlag = FALSE)
for (x in c('age','hyp','chl')) {
regx <- with(data=imp,exp=lm(paste('bmi ~',x)))
summary(pool(regx))
}
然而,R 告诉我 object 'bmi' was not found
.
reg <- with(data=imp,exp=lm(bmi ~ age))
summary(pool(reg))
工作正常,但要求我对列名进行硬编码而不是提供字符串变量。
有办法吗?
通常 lm
接受字符串代替公式,但它似乎不在 with.mids
之内,因此请自行将其转换为公式:
f <- function(nm) {
s <- paste("bmi", nm, sep = "~")
regx <- with(imp, lm(as.formula(s)))
summary(pool(regx))
}
Map(f, names(nhanes)[-2])
注意:您可能希望将此报告给 mice 软件包维护者。