错误消息表明在某些行中存在NAs,R 不会自动排除。首先,我尝试使用fit 和lapop 变量来重现错误消息,并且确实弹出了错误。
margins(fit, design = lapop)
#Error in data.frame(..., check.rows = FALSE, check.names = FALSE, fix.empty.names = FALSE, :
# arguments imply differing number of rows: 6068, 6054
然后,我尝试确认哪个变量有问题NAs。
margins(fit)
#Note: Estimating marginal effects without survey weights. Specify 'design' to adjust for weighting.
#Error in data.frame(..., check.rows = FALSE, check.names = FALSE, fix.empty.names = FALSE, :
# arguments imply differing number of rows: 6068, 6054
弹出相同的错误消息,所以我相信fit 包含NAs。然后我检查了fit 在你的代码中是如何产生的:
fit<-svyglm(ctol ~ y16 + age,
design = lapop,
family = quasibinomial(link = 'logit'))
NAs 应该位于 ctol、y16 或 age 列中的任何一个中。然后,我在age中找到了NAs
> str(df46$age)
dbl+lbl [1:3034] 30, 62, 25, 38, 24, 76, 39, 16, 71, 62, 29, 27, 60, 41, 22, 20, NA, 5...
@ labels: Named num [1:4] NA 888 988 0
..- attr(*, "names")= chr [1:4] "Don't Know" "ns" "nr" "No sabe/No responde"
@ label : chr "Age"
然后,我检查了age 列中有多少个NAs 以及它们的位置。
which(is.na(df46$age))
[1] 17 28 802 888 1045 2401 2898
有 7 个NAs。我怀疑这个数字与错误消息中的数字有关,因为df46 中有 3034 行。将数字加倍,得到 6068。将 NAs 的数量加倍,得到 14,6068-14 = 6054,即错误消息中显示的确切数字。
然后,我尝试排除df46中的七行以获得完整的案例,并使用完整的案例创建lapop和fit。
ind = which(is.na(df46$age))
df46_complete = df46[-ind,]
lapop<-svydesign(ids = ~ upm,
strata = ~ estratopri,
weights = ~ weight1500,
nest = T,
data = df46_complete)
fit<-svyglm(ctol ~ y16 + age,
design = lapop,
family = quasibinomial(link = 'logit'))
最后,当我运行margins()时没有弹出错误:
margins(fit, design = lapop) %>% summary()
# factor AME SE z p lower upper
# age -0.0026 0.0004 -6.0633 0.0000 -0.0035 -0.0018
# y16 0.1323 0.0187 7.0638 0.0000 0.0962 0.1696