【发布时间】:2023-04-04 14:28:01
【问题描述】:
我正在尝试计算数据框的 Spearman 相关性和 p 值。为了更好地逼近 p 值,我必须坚持使用 pspearman 包。我期待与rcorr() 函数相似的结果。但是我在逐行执行pspearman:spearman.test() 时遇到问题。
我的数据框包含 5000 行(基因)和 200 列(点)。我想得到这些 5000*5000 基因-基因对的相关矩阵和 p 值矩阵。仅当两个基因都不是多于两个位点的 NA 时才计算相关性。
我可以通过循环来实现这一点,但对于我的大数据集来说太慢了。当我尝试使用apply(),sapply(),mapply() 来提高速度时遇到问题。
这是我尝试过的:
data = data.frame(matrix(rbinom(10*100000, 50, .5), ncol=200))
dim(data) #5000, 200
rownames(data) <- paste("gene", 1:5000, sep="")
colnames(data) <- paste("spot",1:200,sep='')
library(pspearman)
spearFunc = function(x,y=data) {
df = rbind(x,y)
# Check the number of complete spots.There are no NAs in this set.
complete = sum(!(is.na(x)) & !(is.na(y)))
if (complete >=2 ) {
pspearman::spearman.test(as.numeric(x),as.numeric(y))
# This function returns a list containing 8 values, like pvalue,correlation
}}
pair.all1 = mapply(spearFunc,data,data)
dim(pair.all1)
# 8 200, 200 is the number of columns
pair.all2 = apply(data,1,spearFunc)
这会导致错误:
pspearman::spearman.test(as.numeric(x), as.numeric(y)) 中的错误: (list) 对象不能被强制输入'double'
我希望用spearman.test对每个基因对用apply()来做
spearman.test(data[gene1],data[gene1])
spearman.test(data[gene1],data[gene2])
....
spearman.test(data[gene1],data[gene5000])
...
spearman.test(data[gene5000],data[gene5000])
它应该返回一个 8 行 25,000,000 列(5000*5000 个基因对)的数据框。
是否可以在 apply() 中使用 apply() 来实现我的目的?
谢谢!
【问题讨论】:
标签: r apply correlation sapply mapply