[英]How to use the Box-Tidwell function with a logistic regression in R
[英]How to use logistic regression in R function
I am trying to use r base logistic regression function in my customized r function but my glm()
is not able to recognize my variables. 我在搜索引擎中尝试了多个搜索关键字,但所有答案都与拟合逻辑回归有关。
例如:
第一次尝试:
dat <- data.frame(a = c(3,4,5), b = c("a","a","b"))
logit <- function(dataname, x, y) {
model = glm(y ~ x, data = dataname, family = "binomial")
model
}
logit(dat, a, b)
Error in eval(predvars, data, env) : object 'b' not found
另一种方法:
logit <- function(dataname, x, y) {
model = glm(eval(substitute(y), dat) ~ eval(substitute(x), dat), family = "binomial")
model
}
logit(dat, a, b)
output 会将我的 IV 更改为 eval(substitute(x), dataname) 而不是 x。
glm.fit: fitted probabilities numerically 0 or 1 occurred
Call: glm(formula = eval(substitute(y), dataname) ~ eval(substitute(x),
dataname), family = "binomial")
Coefficients:
(Intercept) eval(substitute(x), dataname)
-208.27 46.34
Degrees of Freedom: 2 Total (i.e. Null); 1 Residual
Null Deviance: 3.819
Residual Deviance: 3.597e-10 AIC: 4
有什么方法可以在 output 中获得正确的 output 和正确的 IV 名称?
谢谢
我同意@IceCreamToucan 的观点,即最好的方法是将公式传递给 function
logit <- function(dataname, formula) {
model = glm(formula, data = dataname, family = "binomial")
model
}
logit(dat, b~a)
否则,您应该先构建公式,然后将其传递给glm
logit <- function(dataname, x, y) {
formula <- reformulate(as.character(substitute(x)), as.character(substitute(y)))
model = glm(formula, data = dataname, family = "binomial")
model
}
logit(dat, a, b)
logit <- function(dataname, x, y) {
model = glm( as.formula(paste(y, "~", x)),
data = dataname,
family = "binomial")
model
}
logit(dat, "a", "b")
如果您有许多解释变量,则可以传入名称向量并使用:
as.formula(paste(y, "~", paste(x, collapse="+")))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.