如何预测随机和固定效应模型?

时间:2015-07-08 17:02:59

标签: r glm predict generic-function

我最近刚从STATA更改为R,并且在实现ST等效命令xtlogit,fe or repredict的R等效方面遇到了一些麻烦。我可以请求一些帮助来调整以下情况:

  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 个答案:

答案 0 :(得分:2)

欢迎来到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类对象的glmpredict.loess类的对象的loess,{{1}的对象的predict.nls }等等(查看完整列表阅读nls帮助)。遗憾的是,不存在predict函数。因此,当您在类predict.glmmML的对象上调用predict函数时,会出现错误。

glmmML

错误非常有用。它基本上说R试图使用S3方法,但是,没有&#39; predict.glmmML&#39;

user227710建议的id <- factor(rep(1:20, rep(5, 20))) y <- rbinom(100, prob = rep(runif(20), rep(5, 20)), size = 1) x <- rnorm(100) dat <- data.frame(y = y, x = x, id = id) fit.2 <- glmmML(y ~ x, data = dat, cluster = id) predict(fit.2) Error in UseMethod("predict") : no applicable method for 'predict' applied to an object of class "glmmML" class(fit.2) [1] "glmmML" 函数怎么样?我们来看看

mclogit

data(Transport) fit <- mclogit( cbind(resp,suburb)~distance+cost, data=Transport ) class(fit) [1] "mclogit" "lm" 的班级是fitmclogitlm会工作吗?是!当您致电predict时,predict(fit)功能将首先查找不存在的predict。接下来会查找predict.mclogit。哪个存在。