【发布时间】: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<-(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