options(stringsAsFactors = F) expdata0 = read.table("~/data_RNA_Seq_v2_mRNA.txt",header=T,sep="\t") View(head(expdata0)) isthereNA <- function(x){ return(any(is.na(x))) } index = apply(expdata0,1,isthereNA) expdata1 = expdata0[!index,] View(head(expdata1)) expdata2 = expdata1[,c(-1,-2)] rownames(expdata2) = expdata1[,1] View(head(expdata2)) gene.wanted = 'EFGL2' gene.wanted.exp = unlist(expdata2[rownames(expdata2) == gene.wanted,]) names(gene.wanted.exp) = NULL ## get correlations with wanted gene getCorrelationPvalue1 <- function(x){ pvalue = cor.test(x,gene.wanted.exp,method = "spearman")$p.value return(pvalue) } getCorrelationPvalue2 <- function(x){ pvalue = cor.test(x,gene.wanted.exp,method = "pearson")$p.value return(pvalue) } getCorrelationValue1 <- function(x){ cor.value = cor.test(x,gene.wanted.exp,method = "spearman")$estimate return(cor.value) } getCorrelationValue2 <- function(x){ cor.value = cor.test(x,gene.wanted.exp,method = "pearson")$estimate return(cor.value) } p.value.spearman = apply(expdata2,1,getCorrelationPvalue1) p.value.pearson = apply(expdata2,1,getCorrelationPvalue2) cor.value.spearman = apply(expdata2,1,getCorrelationValue1) cor.value.pearson = apply(expdata2,1,getCorrelationValue2) result = data.frame(GeneName = names(p.value.spearman), P.value.Spearman = unlist(p.value.spearman), Cor.value.Spearman = unlist(cor.value.spearman), P.value.Pearson = unlist(p.value.pearson), cor.value.pearson = unlist(cor.value.pearson)) result = result[order(abs(result$Cor.value.Spearman),decreasing = T),] View(head(result)) write.table(result,"Coexpression_result.txt",col.names = T,row.names = F,quote=F,sep="\t")