2012-10-26 45 views
1

我想對維度(50x752)的數據幀執行chisq.test。我想獲得所有列的所有可能的paire-wise比較的pvalues(通過多個測試進行調整)。最後,我想返回一個矩陣(50x50)來生成調整後的chisq pvalues的熱圖。這是我現在做的,但這是理想的。R chisq.test()使用二進制比較的數據幀

步驟1:執行pairewise比較

function(data,p.adjust.method="holm") 
{ 
cor.mat <- cor(data) 
x<-ncol(data)#nb of column in matrix here 50 
y<-nrow(data)#nb of column in matrix here 758 
index<-t(combn(x, 2)) #create the matrix position of output for all possible combination 
nindex <- nrow(index) 
pvals <- numeric(nindex) 

for (i in 1:nindex) 
{ 
pvals[i]<-chisq.test(data[, index[i, 1]], data[, index[i,2]])$p.value 
} 
pvals<-p.adjust(pvals,method = p.adjust.method) 
out <- as.data.frame(cbind(index, pvals)) 
} 

步驟2:輸出表是轉換爲使用

dcast(df,V2~V1,fill=1) # thanx to Roland for this function! 

矩陣但這都不盡如人意,因爲我不反映在p值最後一個矩陣和我不得不操縱第一個函數的輸出來得到填充0的對角線(當比較一列到它自己時)。對你的幫助表示感謝!

回答

2

是否這樣?

#some data 
set.seed(42) 
df <- data.frame(a=rbinom(1000,5,0.3), 
       b=rbinom(1000,5,0.001), 
       c=rbinom(1000,5,0.1), 
       d=rbinom(1000,5,0.9)) 

#function to calculate the adj. p-value 
fun <- function(x,y) { 
    p.adjust(chisq.test(df[,x],df[,y])$p.value,method="holm",n=choose(ncol(df),2)) 
} 

p.adj <- outer(names(df),names(df),FUN=Vectorize(fun)) #use outer to get a matrix 
diag(p.adj) <- 1 #you should find out why chisq.test returns zero at the diag 
rownames(p.adj) <- names(df) 
colnames(p.adj) <- names(df) 

p.adj 
# a   b c   d 
#a 1 1.0000000 1 1.0000000 
#b 1 1.0000000 1 0.6152165 
#c 1 1.0000000 1 1.0000000 
#d 1 0.6152165 1 1.0000000 
+0

這簡直太完美了!非常感謝羅蘭,您的幫助非常感謝! :) – OLiviera

+0

+1爲生命,宇宙和一切的答案。 –