进阶篇 04

R语言 for 循环批量操作实战

以单基因批量相关性分析为例,掌握循环的实际应用

📚
学习提示: 本教程内容仅供学习参考,实际应用时请结合具体数据和场景进行调整。 代码和方法可能需要根据实际情况进行修改。
🔄

for循环 是R语言中进行批量操作的基础工具。本文以单基因批量相关性分析为例,展示循环的实际应用场景。

1. 应用场景

假设我们有一个基因表达矩阵,想要:

🎯

选择目标基因

📊

计算与所有基因的相关性

📈

得到相关系数、p值、FDR

2. 数据准备

读取与转置数据

library(tidyverse)

# 读取表达矩阵
load("exprSet.Rdata")
df <- exprSet

# 转置数据:行为样本,列为基因
test <- data.frame(t(df))  # 注意:转置外面记得加data.frame()

单个相关性检验

# 提取两个基因(确保是数值型)
gene1 <- as.numeric(test[, "GAPDH"])
gene2 <- as.numeric(test[, "RACK1"])

# Spearman相关性分析
cor <- cor.test(gene1, gene2, method = "spearman")
cor$p.value     # p值
cor$estimate    # 相关系数

3. 批量相关性分析

循环三步骤

步骤 说明 代码
1. 设置容器 创建空data.frame result <- data.frame()
2. 编写循环 从1到n执行操作 for (i in 1:n) {...}
3. 存储结果 每次循环存入容器 result[i, ] <- ...

完整代码

# 1. 设置容器
correlated <- data.frame()
genelist <- colnames(test)
gene <- "RN7SK"  # 目标基因

# 禁用科学计数法
options(scipen = 200)

# 2. 开始循环
for (i in 1:length(genelist)) {
  print(i)
  
  # 相关性检验
  x <- cor.test(
    as.numeric(test[, gene]),
    as.numeric(test[, i]),
    method = "spearman"
  )
  
  # 3. 存储结果
  correlated[i, 1] = gene
  correlated[i, 2] = genelist[i]
  correlated[i, 3] = x$p.value
  correlated[i, 4] = x$estimate
  
  print(paste0(i, " is done!"))
}

结果整理

# 设置列名
colnames(correlated) <- c("gene1", "gene2", "p_value", "estimate")

# 保留4位小数
correlated$p_value <- round(correlated$p_value, 4)
correlated$estimate <- round(correlated$estimate, 4)

# 计算FDR(多重检验校正)
correlated$FDR <- p.adjust(correlated$p_value, method = "BH")

💡 提示:FDR校正使用 p.adjust() 函数,method = "BH" 表示 Benjamini-Hochberg 方法。

4. 可视化结果

使用 ggstatsplot 包绘制相关性图:

library(ggstatsplot)

ggscatterstats(
  data = test,
  y = RN7SK,
  x = MTCO2P12,
  centrality.para = "mean",
  margins = "both",
  xfill = "#CC79A7",
  yfill = "#009E73",
  marginal.type = "histogram",
  title = "Relationship between RN7SK and MTCO2P12"
)

5. 替代方案:purrr::map

虽然 for 循环基础实用,但 purrr::map 更加优雅:

library(purrr)

result <- map_df(genelist, function(g) {
  cor <- cor.test(
    as.numeric(test[, gene]),
    as.numeric(test[, g]),
    method = "spearman"
  )
  tibble(
    gene1 = gene,
    gene2 = g,
    p_value = cor$p.value,
    estimate = cor$estimate
  )
})

📌 建议:初学者先掌握 for 循环,熟练后再学习 purrr 和 apply 家族。

📝 总结

✅ 循环要点

  • • 设置容器存储结果
  • • print() 显示进度
  • • as.numeric() 确保类型
  • • p.adjust() 多重校正

🚀 进阶方向

  • • apply 家族函数
  • • purrr::map 系列
  • • 并行计算 parallel