除了使用 glm 之外,还有其他方法可以在 R 中拟合泊松模型吗?
Is there an alternative way to fit Poisson model in R besides using glm?
当我尝试在 R 中的给定数据集中拟合泊松模型时出现错误。我正在努力理解错误的原因。
library(COUNT) # Titanic dataset
data("titanic")
library(tidyverse)
# Number of missing values
titanic %>%
map_int(~sum(is.na(.)))
# Fit the Poisson regression model
poifit <- glm(survived ~ class, family = poisson, data = titanic)
titanic2 <- titanic %>%
mutate(across(.cols = everything(), ~as.factor(.)))
poifit2 <- glm(survived ~ class, family = poisson, data = titanic2)
我收到错误:
Warning in Ops.factor(y, 0) : ‘<’ not meaningful for factors
Error in if (any(y < 0)) stop("negative values not allowed for the 'Poisson' family") :
missing value where TRUE/FALSE needed
您可能会感到困惑。您无法将泊松拟合到分类响应中。在将 survival
"yes"/"no" 转换为 0/1 之后,您 可以 将泊松分布拟合到二进制数据,但这实际上没有意义:
glm(as.numeric(survived=="no") ~ class, family = poisson, data = titanic)
明智的做法(可能)是 cross-tabulate 并使用值,例如
cc <- as.data.frame(table(titanic))
glm(Freq ~ ., data = cc, family = poisson)
当我尝试在 R 中的给定数据集中拟合泊松模型时出现错误。我正在努力理解错误的原因。
library(COUNT) # Titanic dataset
data("titanic")
library(tidyverse)
# Number of missing values
titanic %>%
map_int(~sum(is.na(.)))
# Fit the Poisson regression model
poifit <- glm(survived ~ class, family = poisson, data = titanic)
titanic2 <- titanic %>%
mutate(across(.cols = everything(), ~as.factor(.)))
poifit2 <- glm(survived ~ class, family = poisson, data = titanic2)
我收到错误:
Warning in Ops.factor(y, 0) : ‘<’ not meaningful for factors
Error in if (any(y < 0)) stop("negative values not allowed for the 'Poisson' family") :
missing value where TRUE/FALSE needed
您可能会感到困惑。您无法将泊松拟合到分类响应中。在将 survival
"yes"/"no" 转换为 0/1 之后,您 可以 将泊松分布拟合到二进制数据,但这实际上没有意义:
glm(as.numeric(survived=="no") ~ class, family = poisson, data = titanic)
明智的做法(可能)是 cross-tabulate 并使用值,例如
cc <- as.data.frame(table(titanic))
glm(Freq ~ ., data = cc, family = poisson)