我尝试使用以下代码从gnm
对象中提取系数:
library(tidyverse)
library(gnm)
library(broom)
library(haven)
data = read_dta('londondataset2002_2006.dta')
data$ozone10 <- data$ozone/10
# GENERATE MONTH AND YEAR
data$month <- as.factor(months(data$date))
data$year <- as.factor(format(data$date, format="%Y") )
data$dow <- as.factor(weekdays(data$date))
data$stratum <- as.factor(data$year:data$month:data$dow)
data <- data[order(data$date),]
# FIT A CONDITIONAL POISSON MODEL WITH A YEAR X MONTH X DOW STRATA
modelcpr = vector(mode = 'list',length = 12)
for(i in 1:12){
modelcpr1 <- gnm(numdeaths ~ ozone10 +
lag(temperature,i), data=data, family=poisson,
eliminate=factor(stratum))
modelcpr[[i]] = broom::tidy(modelcpr1,conf.int = T, exponentiate = T) %>% slice(n()) %>%
select(estimate, conf.low, conf.high) %>% as.matrix %>% unname
}
#vs
#only for i = 1
modelcpr1 <- gnm(numdeaths ~ ozone10 +
lag(temperature,1), data=data, family=poisson,
eliminate=factor(stratum))
#broom::tidy
broom::tidy(modelcpr1,conf.int = T, exponentiate = T) %>% slice(n()) %>%
select(estimate, conf.low, conf.high) %>% as.matrix %>% unname
数据集和部分代码来自本文:
https://bmcmedresmethodol.biomedcentral.com/articles/10.1186/1471-2288-14-122#Sec13
数据集:https://static-content.springer.com/esm/art%3A10.1186%2F1471-2288-14-122/MediaObjects/12874_2014_1140_MOESM2_ESM.zip
产品编号:https://static-content.springer.com/esm/art%3A10.1186%2F1471-2288-14-122/MediaObjects/12874_2014_1140_MOESM1_ESM.docx
运行forloop后,弹出以下错误:
modelcpr = vector(mode = 'list',length = 12)
for(i in 1:12){
modelcpr1 <- gnm(numdeaths ~ ozone10 +
lag(temperature,i), data=data, family=poisson,
eliminate=factor(stratum))
modelcpr[[i]] = broom::tidy(modelcpr1,conf.int = T, exponentiate = T) %>% slice(n()) %>%
select(estimate, conf.low, conf.high) %>% as.matrix %>% unname
}
Error in profile.gnm(object, which = parm, alpha = 1 - level, trace = trace) :
profiling has found a better solution, so original fit had not converged
In addition: Warning message:
In sqrt((deviance(updated) - fittedDev)/disp) : NaNs produced
其中i = 1。
然而,当我一个接一个地运行for循环时:
> modelcpr1 <- gnm(numdeaths ~ ozone10 +
+ lag(temperature,1), data=data, family=poisson,
+ eliminate=factor(stratum))
>
> #broom::tidy
> broom::tidy(modelcpr1,conf.int = T, exponentiate = T) %>% slice(n()) %>%
+ select(estimate, conf.low, conf.high) %>% as.matrix %>% unname
[,1] [,2] [,3]
[1,] 1.000446 0.9988817 1.002013
我能准确无误地得出结果.有什么我错过的吗?
1条答案
按热度按时间uelo1irk1#
伟大的问题;感谢您提供相关细节。我开始研究
gnm()
的源代码,但无法找出问题的根本原因。我还尝试将for循环转换为函数,并使用lapply()
,Map()
和purrr::map()
,得到了相同的结果。作为一个潜在的解决方法,也许你可以在循环中运行
for (i in 2:12)
,然后“手动”添加i = 1
的有问题的结果,例如。创建于2023-10-11使用reprex v2.0.2
这能解决你的问题吗?