R中的认知逻辑回归建模
Cognitive logistic regression modelling in R
我正在尝试构建一个逻辑回归模型,只要响应变量保持不变,它就能够 运行 无论预测变量的性质如何。这是我想到的示例:
#Take in the data
newdata = read.csv("book1.csv", head = TRUE)
#Store the response variable whose column heading you know beforehand
y = "response.variable"
#Identify the predictor variables (this is where I am stuck)
#Below is the algorithm of what I have in mind though
1) Take remaining column headings except "response.variable"
2) Store them as x = c(other headings)
#Form of model
model.form = reformulate(x, response = y)
#Build model
logit = glm(model.form, family = "binomial", data = newdata)
欢迎提出任何想法。
编辑:
当我使用代码时
glm(y ~., data = newdata)
正如@laterow 所建议的,它给出了一个错误声明:
Error in `contrasts<-`(`*tmp*`, value = contr.funs[1 + isOF[nn]]:
contrasts can be applied only to factors with 2 or more levels
如果您的预测变量是 data.frame 中的所有剩余变量,请使用以下方法 select 它们:
x <- names(newdata)[-which(names(newdata) == "response.variable")]
names()
函数returns中所有变量的名称data.frame。超级有用的 which()
函数 returns 向量中与某些条件表达式匹配的元素的索引。
我正在尝试构建一个逻辑回归模型,只要响应变量保持不变,它就能够 运行 无论预测变量的性质如何。这是我想到的示例:
#Take in the data
newdata = read.csv("book1.csv", head = TRUE)
#Store the response variable whose column heading you know beforehand
y = "response.variable"
#Identify the predictor variables (this is where I am stuck)
#Below is the algorithm of what I have in mind though
1) Take remaining column headings except "response.variable"
2) Store them as x = c(other headings)
#Form of model
model.form = reformulate(x, response = y)
#Build model
logit = glm(model.form, family = "binomial", data = newdata)
欢迎提出任何想法。
编辑: 当我使用代码时 glm(y ~., data = newdata) 正如@laterow 所建议的,它给出了一个错误声明:
Error in `contrasts<-`(`*tmp*`, value = contr.funs[1 + isOF[nn]]:
contrasts can be applied only to factors with 2 or more levels
如果您的预测变量是 data.frame 中的所有剩余变量,请使用以下方法 select 它们:
x <- names(newdata)[-which(names(newdata) == "response.variable")]
names()
函数returns中所有变量的名称data.frame。超级有用的 which()
函数 returns 向量中与某些条件表达式匹配的元素的索引。