【问题标题】:Error in contrasts when running multiple Poisson regression models in R:在 R 中运行多个泊松回归模型时的对比错误:
【发布时间】:2018-05-29 05:42:50
【问题描述】:

我的数据如下所示:

df <- data.frame (
time = rep(c("2010", "2011", "2012", "2013", "2014"),4),
age = rep(c("40-44", "45-49", "50-54", "55-59", "60-64"),4),
weight = rep(c(0.38, 0.23, 0.19, 0.12, 0.08),4),
ethgp = rep(c(rep("M",5),rep("NM",5)),2),
gender = c(rep("M",10), rep("F",10)),
pop = round((runif(10, min = 10000, max = 99999)), digits = 0),
count = round((runif(10, min = 1000, max = 9999)), digits = 0)
)

df <- df %>%
mutate(rate = count / pop,
     asr_rate = (rate * weight)*100000, 
     asr_round = round(asr_rate, digits = 0))

首先,我从数据框中删除所有零值

 df <- df [apply(df!=0, 1, all),]

然后我运行以下代码,为该数据中的每个子组(年龄、性别和年份)运行多个泊松回归模型;比较种族群体(M / NM)。我想为所有子组生成比率和 CI,将 M 与 NM 进行比较。

Poisson_test <- df %>% group_by(time, gender, age) %>% 
do({model = glm(asr_round ~ relevel(ethgp, ref = 2), family = "poisson", data = .);
data.frame(nlRR_MNM = coef(model)[[2]], SE_MNM = summary(model)$coefficients[,2][2])})

此代码适用于上述示例。

但是,当我在我的实际数据集上运行此代码时,我收到以下错误消息:Error in contrasts&lt;-(tmp, value = contr.funs[1 + isOF[nn]]) : contrasts can be applied only to factors with 2 or more levels

因为我只有一个解释变量 ethgp,所以我认为这是错误的根源?

我测试了我的数据(不是样本数据)中是否有级别:

str(M_NM_NZ$ethgp)

R 回复:Factor w/ 2 levels "M","NM": 1 1 1 1 1 1 1 1 1 1 ...

我检查了 ethgp 中是否有 NA 值

sum(is.na(M_NM_NZ%ethgp))

R 回复[1] 0

我可能会收到此错误消息还有其他原因吗?

我看过这个问题Error in contrasts when defining a linear model in R 但是在这个例子中,听起来解释变量的格式不正确,或者有 NA 值。在我的数据中并非如此。我可能会收到此错误还有其他原因吗?

【问题讨论】:

    标签: r poisson factors levels contrast


    【解决方案1】:

    我不明白当一个因素确实有多个级别时导致此错误的根本问题。

    在这种情况下,我通过将 ethgp 变量转换为数值变量来解决此问题。

    df <- df %>%
    mutate(ethnum = ifelse(ethgp == "M", 1, 0))
    

    然后使用 ethnum 作为解释变量运行回归。

    Poisson <- df %>% group_by(time, gender, age) %>% 
    do({model = glm(asr_round ~ ethnum, family = "poisson", data = .);
    data.frame(nlRR_MNM = coef(model)[[2]], nlUCI = confint(model)[2,2], nlLCI = confint(model)[2,1])})
    Poisson <- mutate(Poisson,
                  RR_MNM = round(exp(nlRR_MNM),digits = 3),
                  UCI = round(exp(nlUCI),digits = 3),
                  LCI = round(exp(nlLCI),digits = 3))
    

    此代码还计算每个比率的上下 95% 置信区间。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-19
      • 2018-05-21
      • 2021-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多