我知道如何使用R中的 lme4 包拟合广义线性模型 ( GLM )和广义线性混合模型 ( GLMM ) 。作为一名统计学专业的学生,我有兴趣学习如何按照基于R代码的分步公式来拟合GLM 和GLMM 。如果您在这方面指出任何资源和/或参考资料,我将不胜感激。提前致谢。glm
glmer
编辑
我想使用公式一步一步地做GLM和GLMM ,就像我们使用矩阵方法做LM一样。有没有使用这种方法的R书籍或教程?谢谢
这可能会有所帮助
** Poisson 回归:GLM**
*推荐阅读:广义线性模型简介,Annette J. Dobson,第 2 版,第 4 章,第 4.3 和 4.4 节 *
library(MASS)
poisreg = function(n, b1, y, x1, tolerence) { # n is the number of iteration
x0 = rep(1, length(x1))
x = cbind(x0, x1)
y = as.matrix(y)
w = matrix(0, nrow = (length(y)), ncol = (length(y)))
b0 = b1
result = b0
for (i in 1:n) {
mu = exp(x %*% b0)
diag(w) = mu
eta = x %*% b0
z = eta + (y - mu) * (1/mu) # dot product of (y - mu) & (1/mu)
xtwx = t(x) %*% w %*% x
xtwz = t(x) %*% w %*% z
b1 = solve(xtwx, xtwz)
if(sqrt(sum(b0 - b1)^2) > tolerence) (b0 <- b1)
result<- cbind(result,b1) # to get all the iterated values
}
result
}
x1 <- c(-1,-1,0,0,0,0,1,1,1) # x1 is the explanatory variable
y<- c(2,3,6,7,8,9,10,12,15) # y is the dependent variable
b1 = c(1,2) # initial value
poisreg (10, b1, y, x1, .001) # Nicely converge after 10 iterations
glm(y~x1, family=poisson(link="log")) # check your result with the R GLM program
Fox 和 Weisberg 的“An R Companion to Applied Regression”在第 8 章中有一个很好的指南,以逻辑回归为例。这本书还教了一些关于如何使用 S3 和 S4 对象创建模型函数的知识。特别是,它很好地回答了我最近提出的一个关于建模的问题——R中标准模型对象的关键组件和功能是什么?.