我刚刚从STATA更改为R,并且在实现RATA等效的STATA命令 xtlogit,fe or re
和 predict
时遇到了一些麻烦 . 我可以请求一些帮助来调整以下场景:
data <- read.table("http://people.stern.nyu.edu/wgreene/Econometrics/healthcare.csv",header=TRUE, sep=",", na.strings="NA", dec=".", strip.white=TRUE)
require(caret) # for confusionMatrix
#### subset into test & train according to the panel nature (split individuals rather then observations)
nID <- length(unique(data$id))
p = 0.50# partition
inTrain <- sample(unique(data$id), round(nID * p), replace=FALSE)
training <- data[data$id %in% inTrain, ]
testing <- data[!data$id %in% inTrain, ]
pooled <- glm(WORKING~WHITEC+FEMALE+BLUEC+HHNINC+AGE+AGESQ+EDUC+DOCVIS,data=training, family=binomial(link="logit"))
prediction.working= round(predict(pooled,newdata=testing,type="response"))
confusionMatrix(prediction.working,testing$WORKING) # Accuracy between both
另外,我想对随机效果和固定效果做这些程序 . 所以我首先尝试了随机效果:
library(glmmML)
RE <- glmmML(WORKING~WHITEC+FEMALE+BLUEC+HHNINC+AGE+AGESQ+EDUC+DOCVIS, family=binomial(link="logit"), data=training, cluster=id, method="ghq", n.points=12)
prediction.working= round(predict(RE,newdata=testing,type="response"))
但这似乎不起作用 . 请问如何调整有关随机效果和固定效果的 glm
模型以便使用 predict
功能 .
1 回答
欢迎来到R.我也是STATA转换 .
这是一个棘手的问题,但其答案对于理解至关重要 . 要理解为什么
predict
函数不适用于glmmML,您需要了解S3方法(请参阅http://adv-r.had.co.nz/OO-essentials.html) .让我解释一下 . R是面向对象的语言 . 这意味着R中的所有内容都是一个对象(即矢量,函数,data.frame) . 每个对象都包含属性 . 属性本质上是关于对象本身的元数据 . 例如,data.frame中的变量名称是属性 . 所有对象具有的一个属性是类 . 要查看任何对象的类,只需调用
class()
函数即可 .很多(但不是全部)函数使用S3方法 .
predict
函数是这些函数之一 . 这意味着当您调用predict
时,predict
函数会查看对象的类 . 然后根据类别选择应该使用其他预测函数 . 例如,如果您的对象是类lm
,则预测函数将调用predict.lm
函数 . 其他predict
函数包括:predict.glm
用于glm
类的对象,predict.loess
用于loess
类的对象,predict.nls
用于nls
类的对象等(要查看完整列表,请阅读predict
帮助) . 不幸的是,没有predict.glmmML
函数存在 . 因此,当您在类glmmML
的对象上调用predict
函数时,会出现错误 .错误非常有用 . 它基本上说R试图使用S3方法,但是,没有'predict.glmmML'
用户227710建议的
mclogit
函数怎么样?让我们来看看fit
的类是mclogit
和lm
.predict
会工作吗?是!当你调用predict(fit)
时,predict
函数将首先查找predict.mclogit
,它不存在 . 接下来会查找predict.lm
. 哪个确实存在 .