我正在使用阈值规则创建二进制因变量
# here a simple dataset such as
x <- rnorm(n = 50, mean = 1, sd = 3)
names1 <- c(rep("gold", 10), rep("silver", 20), rep("bronze", 20))
df <- data.frame(names1, x)
thresholds <- c("L1", "L3")
logit_conditions <- c(function(x) ifelse(x >= 1, 1, 0),
function(x) ifelse(x >= 3, 1, 0))
dat <- df[0]
for (i in 1:length(logit_conditions)) dat[i] <- logit_conditions[[i]](df$x)
colnames(dat) <- c("L1", "L3")
df <- data.frame(df, dat)
然后我运行一个简单的逻辑回归,该回归在R控制台和Rmarkdown中都可以正常运行。
fit <- glm(L1 ~ x, data = df, family = "binomial")
当我尝试通过lapply创建具有相同公式和不同DV的许多回归时,出于类似SO帖子(Repeat regression with varying dependent variable,R Multiple Regression Loop and Extract Coefficients)的精神,以下代码仅从R控制台运行,而在Rmarkdown中找不到因变量。我究竟做错了什么?
model1 <- lapply(thresholds, function(dv) {
fit <- glm(get(dv) ~ x, data = df, family = "binomial")
})