Goo*_*gme 6 r generic-function predict glm
我最近刚做从STATA于R的改变,并有一些麻烦实施将R等价的命令,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
Run Code Online (Sandbox Code Playgroud)
另外,我想对随机效果和固定效果做这些程序.所以我首先尝试了随机效果:
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"))
Run Code Online (Sandbox Code Playgroud)
但这似乎不起作用.我可以询问如何调整glm关于随机效果和固定效果的模型以便使用该predict功能.
欢迎来到 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.lm函数。其他predict函数包括:predict.glm用于glm类的对象、predict.loess用于loess类的对象、predict.nls用于nls类的对象等(要查看完整列表,请阅读predict帮助)。不幸的是,不predict.glmmML存在任何功能。predict因此,当您在类的对象上调用该函数时glmmML,您会收到错误。
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"
Run Code Online (Sandbox Code Playgroud)
该错误信息非常丰富。它基本上说 R 尝试使用 S3 方法,但是没有“predict.glmmML”
mclogituser227710建议的功能怎么样?让我们来看看
data(Transport)
fit <- mclogit(
cbind(resp,suburb)~distance+cost,
data=Transport
)
class(fit)
[1] "mclogit" "lm"
Run Code Online (Sandbox Code Playgroud)
的类别fit是mclogit和lm。将predict工作?是的!当您调用predict(fit)该predict函数时,将首先查找predict.mclogit不存在的 a 。接下来它将寻找predict.lm. 这确实存在。