【发布时间】:2019-12-17 17:39:39
【问题描述】:
我正在尝试在数据集的不同子集上运行多个逻辑回归模型,然后得出一些预测。但是,当我尝试自动化此过程时; rms 包一直给我带来问题。
模拟数据集:
library(rms)
library(tidyverse)
set.seed(123)
df <- tibble(country = sample(LETTERS[1:7], 100, replace = TRUE),
y = rnorm(100),
x = rnorm(100),
category = sample(letters[1:4], 100, replace = TRUE),
binary = sample(c(TRUE, FALSE), 100, replace = TRUE))
模仿我创建的产生错误的函数:
frm <- "category + x * binary"
frm_nocat <- "x * binary"
mod_filter <- quos(TRUE, category %in% c("a", "b"), category == "a", category == "b")
mod_form <- c(frm, frm, frm_nocat, frm_nocat)
run_rms <- function(dt, formula) {
dt <- droplevels(dt)
on.exit(options(datadist = NULL))
fit <- lrm(as.formula(paste0("y ~", formula)),
x=TRUE, y=TRUE,
data= dt)
rob <- robcov(fit, cluster=dt$country)
dd <- datadist(dt)
options(datadist = "dd")
pred <- Predict(rob, fun = plogis)
list(fit, rob, pred)
}
robust_mods <- map2(mod_filter, mod_form, ~run_rms(filter(df, !!.x), .y)) %>% transpose()
#> Error in Predict(x = rob, fun = plogis, name = "category"): object 'rob' not found
但是,如果我在全球环境中一步一步地这样做,它就会起作用。
filt_df <- filter(df, category %in% c("a", "b"))
fit <- lrm(y ~ category + x * binary,
x=TRUE, y=TRUE,
data= filt_df)
rob <- robcov(fit, cluster=filt_df$country)
dd <- datadist(filt_df)
options(datadist = "dd")
pred <- Predict(rob, fun = plogis)
plot(pred)
感谢大家的指点
【问题讨论】:
-
你能展示如何为一个数据子集运行这个吗?
-
Ronak,感谢您的快速回复。我希望我现在说得更清楚了。