[英]pairwise combinations of coefficient and correlation p.value?
我想按列计算矩阵的系数和相关p值的成对组合。
这里我使用两个函数:
allCoef<- function(Y,X) { lm(Y~X+0)$coef }
allCorr.p<- function(Y,X) { cor.test(Y,X)$p.value }
例如,我有一个A矩阵:
A= matrix(sample(1:100,16),4,4)
apply(Y=A,2,allCoef,X=A)
工作正常。
apply(Y=A,2,allCorr.p,X=A)
但是,在cor.test.default(Y, X) : 'x' and 'y' must have the same length
显示Error cor.test.default(Y, X) : 'x' and 'y' must have the same length
。 有人可以告诉我这里做错了什么吗? 我使用相同的矩阵,因此列的长度应该相同。
您可以使用combn
函数生成列比较的所有组合,然后使用cor.test
在A
的列组合中应用此矩阵(假设A在您的全局环境中可用):
# All combinations of pairwise comparisons
cols <- t( combn(1:4,2) )
apply( cols , 1 , function(x) cor.test( A[,x[1] ] , A[ , x[2] ] )$p.value )
#[1] 0.9893876 0.9844555 0.5461623 0.7987615 0.7414658 0.1061751
由combn
函数生成的列的成对组合是:
[,1] [,2]
[1,] 1 2
[2,] 1 3
[3,] 1 4
[4,] 2 3
[5,] 2 4
[6,] 3 4
你的apply(Y=A,2,allCorr.p,X=A)
没有按预期工作,因为(无论你不需要使用Y=A
)你将整个矩阵作为第二个参数传递给你的函数,所以X
实际上具有矩阵中所有列的长度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.