7

我最近刚刚从 STATA 更​​改为 R,并且在实现 STATA 命令的 R 等效项xtlogit,fe or repredict. 我可以请求一些帮助来调整以下场景:

  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功能。

4

1 回答 1

4

欢迎来到 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函数会查看对象的类。然后根据班级选择应该使用哪个其他预测功能。例如,如果您的对象是 class lm,则 predict 函数将调用该predict.lm函数。其他predict功能包括:类predict.glm对象、类对象、类对象等(查看完整列表阅读帮助)。不幸的是,不存在任何功能。因此,当您在类的对象上调用该函数时,您会得到一个错误。glmpredict.loessloesspredict.nlsnlspredictpredict.glmmMLpredictglmmML

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"

该错误信息非常丰富。它基本上说 R 尝试使用 S3 方法,但是,没有“predict.glmmML”

mclogituser227710 建议的功能怎么样。让我们来看看

data(Transport)

fit <- mclogit(
  cbind(resp,suburb)~distance+cost,
  data=Transport
)

class(fit)
[1] "mclogit" "lm"

的类fitmclogitlm。会predict工作吗?是的!当您调用predict(fit)predict函数时,将首先查找一个predict.mclogit不存在的 。接下来它会寻找predict.lm. 确实存在。

于 2015-07-08T21:45:24.360 回答