微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何将 p.adjust 应用于 R 中矩阵中的每一行?

如何解决如何将 p.adjust 应用于 R 中矩阵中的每一行?

我有一个 100 x 10 000 矩阵,其 p 值 (pval) 对应于 100 个假设的 10 000 次重复。 现在我想使用函数 p.adjust 对矩阵中的每一行应用 bonferroni 校正。

我的代码运行了,但与原始 p 值矩阵相比,p 值没有变化,与预期的 0.05 水平相比,FWER 仍约为 0.994。

之前我尝试使用 apply 代替,但意识到我想要调整每一行,sapply 应该更合适。

这是我的代码

#we simulate n random variables and test the null hypothesis that all
#means are simultaneously 0. (case where all nulls are true.)
n <- 100
pval <- matrix(NA,nrow = 1e4,ncol = n) #making matrix for data
for(k in 1 : 1e4){
  X <- replicate(n=n,expr = rnorm(100)) #replicate makes a matrix with n columns and 100 rows of norm(1,0)
  pval[k,] <-  apply(X=X,MARGIN = 2,FUN = function(x){ #apply applies a function on our X matrix. MARGIN = 2 means the function is applied on the columns.
    t.test(x = x,mu = 0)$p.value #the function being applied is t.test. (t test is taken on all columns in the X matrix (100 rows))
  }) #this returns a matrix with n rows,10000 columns where each column represents a p-value.
} #the data is uncorrelated. all zero - hypotheses are true.

#Now we apply the Bonferroni correction:
padjBonf <- matrix(NA,ncol = n) #making matrix for adjusted p-vals
for(k in 1 : 1e4){
  padjBonf[k,] <- sapply(X = pval[k,],FUN = function(x){ #sapply applies a function on our X vector. MARGIN = 2 means the function is applied on the columns.
    p.adjust(x,method = "bonferroni") 
  }) 
} 

解决方法

像在单个值

上运行p.adjust一样使用sapply

注意以下事项:

p.adjust( 0.05,method="bonferroni" ) # returns 0.05,unchanged!

这就是你所经历的。

您可能打算给 p.adjust all 每个实验的 p 值,因此您的 p.val 的整个行,如下所示:

padjBonf[k,] = p.adjust( p.val[k,],method="bonferroni" )

这应该返回所有 1 作为适当的。

或者您可以继续更正每个 p 值并告诉它手册中记录的 n=100,但实际上没有必要,并且 p.adjust 是在考虑上述用法的情况下编写的。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。