NA/NaN/Inf in foreign function error with mantelhaen.test()



我有一个 100k 行的数据帧,我想在其上计算 Cochran-Mantel-Haenszel 检验。

我的变量是教育水平和以分位数为单位的计算分数,我的分组变量是性别,代码行如下所示:

mantelhaen.test(db$education, db$score.grouped, db$sex)

此代码抛出此错误并警告:

qr.default(a, tol = tol) 中的错误:外来函数调用中的 NA/NaN/Inf (arg 1)
此外: 警告消息: 在 ntot * 行和中:整数溢出产生的 NA

该错误似乎是由我的第一个变量引起的,因为在测试的 7 个变量中,我只遇到了其中 2 个变量的问题,这似乎没有明显的共同点。

缺失值和因子水平在引发错误的变量和不抛出错误的变量之间似乎没有区别。我尝试了完整的案例(na.omit),但问题仍然存在。

什么触发此错误? 这是什么意思?
我怎样才能摆脱它?

有趣的帖子 : R: 外来函数调用中的 NA/NaN/Inf (arg 1), 什么是 R 中的整数溢出,它是如何发生的?

附录:这是str的结果(失败educationimc.cl):

str(db[c("education","score.grouped","sex", ...)])
'data.frame':   104382 obs. of  7 variables:
$ age.cl: Ord.factor w/ 5 levels "<30 ans"<"30-40 ans"<..: 5 2 1 1 3 4 2 3 4 4 ...
..- attr(*, "label")= chr "age"
$ emploi2          : Factor w/ 8 levels "Agriculteurs exploitants",..: 3 5 6 8 8 8 8 3 3 3 ...
..- attr(*, "label")= chr "CSP"
$ tabac            : Factor w/ 4 levels "ancien fumeur",..: 4 1 4 4 3 4 4 1 4 4 ...
..- attr(*, "label")= chr "tabac"
$ situ_mari2       : Factor w/ 3 levels "Vit seul","Divorsé, séparé ou veuf",..: 3 2 1 1 1 3 1 3 2 3 ...
..- attr(*, "label")= chr "marriage"
$ education        : Factor w/ 3 levels "Universitaire",..: 1 1 1 1 3 1 1 1 1 1 ...
$ revenu.cl        : Factor w/ 4 levels "<1800 euros/uc",..: 3 4 2 NA 4 1 1 4 4 1 ...
$ imc.cl           : Ord.factor w/ 6 levels "Maigre"<"Normal"<..: 2 2 1 2 3 1 3 2 2 3 ...
..- attr(*, "label")= chr "IMC"

编辑:通过深入研究函数,错误和警告是由调用qr.solve引起的。我对此一无所知,但我会尝试更深入地研究
EDIT2:在qr.solve内部,错误是由对.F_dqrdc2Fortran调用引发的。这远远超出了我的水平,我的鼻子开始流血。
编辑3:我试图head我的数据以找出哪一行是原因:

db2 = db %>% head(99787)   #fails at 99788
db2 = db %>% tail(99698)   #fails at 99699
mantelhaen.test(db2$education, db2$score.grouped, db2$sex)

这给我的信息不多,但也许它可以给你。

我能够通过使数据集更大来复制问题。

set.seed(101); n <- 500000
db <- data.frame(education=
factor(sample(1:3,replace=TRUE,size=n)),
score=
factor(sample(1:5,replace=TRUE,size=n)),
sex=
sample(c("M","F"),replace=TRUE,size=n))

在此之后,mantelhaen.test(db$education, db$score, db$sex)给出报告的错误。

值得庆幸的是,真正的问题不在 QR 分解代码的内脏中:相反,它发生在 QR 分解之前设置矩阵时。有两个计算,ntot*colsumsntot*rowsums,溢出了R的整数计算能力。有一种相对简单的方法可以通过创建函数的修改版本来解决此问题:

  • 复制源代码:dump("mantelhaen.test",file="my_mh.R")
  • 编辑源代码
    • l. 1:将函数名称修改为my_mantelhaen.test(避免混淆)
    • 第 199 行和第 200 行:将ntot更改为as.numeric(ntot),在溢出发生之前将整数转换为双精度
  • 在新函数中读取source("my_mh.R")

现在

my_mantelhaen.test(db$education, db$score, db$sex)  

应该工作。 对于新函数起作用的情况,您绝对应该针对旧函数测试它,以确保您得到相同的答案。

现在发布到 R 错误列表,我们将看到会发生什么......

2018 年 5 月 11 日更新:这在 R 的开发版本(3.6 待 be)中已修复。

最新更新