在函数中添加na.omit作为参数

时间:2013-05-24 12:53:47

标签: r na

我有以下pval列表

pval.list <- list(list(a=c(0.05, 0.0001, 0.32, 0.45), b=c(0.1,0.12,0.01,0.06), c=c(0.1,0.12,0.01,0.06), d=c(0.01,0.02,0.03,0.04)),
         list(e=c(0.04, NA, 0.232, 0.245), f=c(0.05, 0.01, 0.22, 0.54), g=c(0.005, 0.1, 0.032, 0.045)),
         list(h=c(0.03, 0.01, NA, 0.4), i=c(0.5, 0.0001, 0.132, 0.045), j=c(0.005, 0.0001, 0.0032, 0.045), k=c(0.5, 0.1, 0.932, 0.545)),
         list(l=c(0.022, NA, 0.32, 0.45), m=c(0.0589, 0.0001, NA, 0.0045)),
         list(n=c(0.051, 0.01, 0.32, 0.45), o=c(0.05, 0.0001, 0.32, 0.45), p=c(0.05, 0.0001, 0.32, 0.45), q=c(0.05, 0.0001, NA, 0.45)),
         list(r=c(NA, 0.001, 0.32, 0.45), s=c(0.05, 0.0001, NA, 0.45), t=c(0.05, 0.0001, 0.32, 0.45)))

我正在尝试将一个函数(见下文)应用于此列表:

Fisher.test <- function(p) {
Xsq <- -2*sum(log(p))
p.val <- 1-pchisq(Xsq, df = 2*length(p))
return(p.val) 
}

根据@ G.Grothendieck的指示,我使用了这个命令:lapply(lapply(pval.list, Reduce, f = cbind), apply, 1, Fisher.test)但是当列表中缺少值时,方法不起作用。我已尝试将na.omit作为参数合并到lapply,但它无法解决问题。

我应该在na.omit函数中添加Fisher.test作为参数吗?

由于

1 个答案:

答案 0 :(得分:1)

您的NAs是在sum中生成的。如果您传递参数na.rm=TRUE,则结果中不会有NA:

Xsq <- -2*sum(log(p), na.rm=TRUE)

您可以为na.rm制作Fisher.test参数,并从lapply传递真或假,但当总是想要排除NAs时,您应该只是在函数中设置参数。

在你的pvalues上调用函数:

lapply(lapply(pval.list, Reduce, f = cbind), apply, 1, Fisher.test)

给出:

[[1]]
[1] 1.953968e-03 2.999509e-05 5.320831e-04 1.339104e-02

[[2]]
[1] 0.0007878665 0.0317662968 0.0457435481 0.1146067577

[[3]]
[1] 8.982382e-03 3.055250e-08 4.719676e-02 5.094879e-02

[[4]]
[1] 0.009911091 0.001021034 0.684618971 0.014584426

[[5]]
[1] 2.357950e-03 6.135981e-11 5.543601e-01 6.038488e-01

[[6]]
[1] 6.235072e-02 3.470933e-09 6.016501e-01 5.708789e-01

现在在计算总和之前删除所有NA值。 这样做你想要的吗?