[英]Iterative spearman correlation with cor.test?
我是R的初学者,尝试在R中创建迭代cor.test时遇到一些问题。我有一张表格,其中包含8个不同的采样点(第1列至第8列),对于每个采样点,我都测量了一个变量(VARIABLE1,第一行)和一系列物种的存在(行上的OTU)。 在这里,您可以看到我的表的摘录(称为“矩阵”):
row.names 1 2 3 4 5 6 7 8
VARIABLE1 1565 1809,83 1019 1909,83 756,33 631,67 529,83 436
OTU1 0 0 0 0 0 3 0 0
OTU2 0 0 0 0 0 0 13 0
OTU3 5 0 0 0 0 0 0 0
OTU4 0 0 0 0 0 0 0 0
OTU5 0 0 0 0 0 0 0 2
OTU6 0 0 19 0 9 236 59 2
OTU7 0 0 0 2 4 2 3 0
OTU8 0 0 10 5 0 0 7 0
OTU9 6 0 13 2 0 0 17 6
OTU10 0 0 0 0 0 3 0 0
OTU11 4 13 0 0 2 1 2 0
OTU12 0 0 0 0 0 101 1 0
我想计算VARIABLE1与每个OTU之间的Spearman相关性。 因此,VARIABLE1必须保持固定,而OTU必须每次都更改。
我尝试使用“ lapply”,但没有成功:
flip_matrix <- t(matrix)
variable1 <- flip_matrix[,1]
lapply(flip_matrix[1:107], function(x) cor.test(x, variable1, alternative='two.sided', method='spearman'))
Error in cor.test.default(x, shoot_growth, alternative = "two.sided", :
'x' e 'y' must be of the same length
我怎么解决这个问题? 谢谢大家!!
使用Apply而不是循环。 您还将获得测试的p值。
df <- read.table(header=T,dec=",",text=c("row.names 1 2 3 4 5 6 7 8
VARIABLE1 1565 1809,83 1019 1909,83 756,33 631,67 529,83 436
OTU1 0 0 0 0 0 3 0 0
OTU2 0 0 0 0 0 0 13 0
OTU3 5 0 0 0 0 0 0 0
OTU4 0 0 0 0 0 0 0 0
OTU5 0 0 0 0 0 0 0 2
OTU6 0 0 19 0 9 236 59 2
OTU7 0 0 0 2 4 2 3 0
OTU8 0 0 10 5 0 0 7 0
OTU9 6 0 13 2 0 0 17 6
OTU10 0 0 0 0 0 3 0 0
OTU11 4 13 0 0 2 1 2 0
OTU12 0 0 0 0 0 101 1 0"))
dft <- t(df[,-1])
res <- apply(dft[,-1], 2, function(x,y) cor.test(x,y,method = "spearman"),dft[,1])
data.frame(do.call(rbind,res))
或使用Hmisc软件包的rcorr函数
library(Hmisc)
rcorr(dft,type = "spearman")
你的意思是这样吗?
matrix <- matrix(
c(1565, 1809.83, 1019, 1909.83, 756.33, 631.67, 529.83, 436,
0, 0 , 0 , 0 ,0 ,3 ,0 ,0,
0, 0, 0 , 0 ,0 ,0 ,13 ,0,
5 , 0 , 0 , 0 ,0 ,0 ,0 ,0,
0 , 0, 0 , 0 ,0 ,0 ,0 ,0,
0 , 0 , 0 ,0 ,0 ,0 ,0 ,2,
0 , 0 , 19 ,0 ,9 ,236 ,59 ,2,
0 , 0 , 0 ,2 ,4 ,2 ,3 ,0,
0 , 0 , 10 ,5 ,0 ,0 ,7 ,0,
6 , 0 , 13 ,2 ,0 ,0 ,17 ,6,
0, 0 , 0 ,0 ,0 ,3 ,0 ,0,
4, 13, 0 ,0 ,2 ,1 ,2 ,0,
0 , 0 , 0 ,0 ,0 ,101 ,1 ,0), ncol = 8, byrow = T)
rownames(matrix) = c("VARIABLE1", paste("OTU", 1:12, sep = ""))
test <- list()
for (i in 2:nrow(matrix)) {
test[[i]] <- cor.test(x = matrix[1,], y = matrix[i,], alternative="two.sided", method="spearman")
}
但是,由于样本量太小,我确实收到警告消息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.