paired t-test crashes apply-loop (edited)

烈酒焚心 提交于 2019-12-03 20:54:56
Aaron - Reinstate Monica

In situations like this, I catch all the warnings and errors and investigate them afterwards, as shown here: How do I save warnings and errors as output from a function?

You may also find some good ideas here: How to tell lapply to ignore an error and process the next thing in the list?

UPDATE Since you said that the for-loop ALSO give the error and you want the apply version to be more robust, why not simply add a tryCatch?

pv.list <- apply(table[,2:9],1, function(x) tryCatch( 
  t.test(x[1:4],x[5:8],paired=TRUE)$p.value, error=function(x) NA ))

This should return NA if the p.value could not be calculated. You could change to another value (e.g. NULL, 0 or Inf) by editing the error handling function.

Old Post

I noted that t.test (kind of) gives the error you found when some values are Inf (which seems to be a bug):

> t.test(1:10, c(rep(1,9), Inf), paired=TRUE)
Error in if (stderr < 10 * .Machine$double.eps * abs(mx)) stop("data are essentially constant") : 
missing value where TRUE/FALSE needed

So do you actually get this or does it actually say:

Error in t.test: data are essentially constant

Still not quite clear why the for-loop works though. But note that in your for-loop you do as.numeric, which you don't do in the apply case...

t.test(rep(1,4),rep(0,4))would report the same error. And https://stat.ethz.ch/pipermail/r-help/2008-February/154167.html is the answer to deal with 1) zero-variance 2) observation number is not ≥ 1

I've run into exactly this problem, using tapply to run a large number of paired t-tests. I use sample size as a guide to remove data that I probably shouldn't be running t-tests on anyways.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!