R

# 1. 单个基因和免疫细胞相关性分析

## 1.1 for循环计算

``````gene <- "KLF5"
y <- as.numeric(expr_data[,gene])

### 批量操作的具体实现过程：
### 1.设定容器,最终生成的数据放在什么地方？
correlation <- data.frame()

### 2.批量把数据导出到容器
for(i in 1:length(colnames(immu_data))){
## 1.指示
print(i)
## 2.计算
dd = cor.test(as.numeric(immu_data[,i]),y,method="spearman")
## 3.填充
correlation[i,1] = colnames(immu_data)[i]
correlation[i,2] = dd\$estimate
correlation[i,3] = dd\$p.value
}
### 修改名称
colnames(correlation) <- c("cell","cor","p.value")
``````

## 1.2 lapply 计算

``````yourgene <- 'DDR1'
genelist <- colnames(immu_data)
# 写一个函数
mycor <- function(x){
dd = cor.test(expr_data[,yourgene], immu_data[,x], method = 'spearman')
data.frame(gene = yourgene, cell = x, R = dd\$estimate, p.value = dd\$p.value)
}

# 测试一下
mycor(genelist[1])

# 批量
lapplylist <- lapply(genelist, mycor)

# do.call
cor_data <- do.call(rbind, lapplylist)

# 整理成一个函数
cor_data <- do.call(rbind, lapply(genelist, function(x){
dd = cor.test(COAD_data[,yourgene], COAD_data[,x], method = 'spearman')
data.frame(gene1 = yourgene, gene2 = x, R = dd\$estimate, p.value = dd\$p.value)
}))
``````

# 多个基因怎么计算

``````sig_gene <- c("APOE","CASR","CTLA4", "CXCL8", "F2","IL6","MMP9")

library(psych)
x <- expr_data[,sig_gene]
y <- immu_data

library(psych)
d <- corr.test(x,y,use="complete",method = 'spearman')

r <- d\$r
p <- d\$p

library(ggcorrplot)
ggcorrplot(t(d\$r), show.legend = T,
p.mat = t(d\$p.adj), digits = 2,  sig.level = 0.05,insig = 'blank',lab = T)
``````