我有这样的数据:
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))首先,我从dataframe中删除所有的零值。
df <- df [apply(df!=0, 1, all),]然后,我运行以下代码,以运行多个Poisson回归模型,对数据中的每个子组(年龄、性别和年份);比较族裔群体(M / NM)。我想为所有的子群生成速率比,比较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值。在我的数据中,情况并非如此。还有其他原因我可能会犯这个错误吗?
发布于 2018-05-29 23:55:46
当一个因素确实有一个以上的级别时,我不理解导致这个错误的潜在问题。
在这个例子中,我通过将ethgp变量转换成一个数值变量来解决这个问题。
df <- df %>%
mutate(ethnum = ifelse(ethgp == "M", 1, 0))然后使用民族作为解释变量运行回归。
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%置信区间。
https://stackoverflow.com/questions/50577042
复制相似问题