[英]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.