You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

列数相同行数不同的数据框执行corr.test报错,如何正确做相关性检验?

问题分析与解决

错误原因

你用错了corr.test()的使用场景:这个函数要求输入的两个数据框行数完全一致,因为它默认是按行配对做相关性分析(即每一行对应同一个样本的两组指标)。但你的cesc_test(139行)和hnsc_pos_test(70行)是两组完全独立的样本,行数不匹配,因此触发了维度不兼容的错误。

方法是否正确?

完全不正确。你的需求是对比HPV+头颈癌和HPV+宫颈癌的xCell细胞类型得分,但corr.test()是用于配对样本的指标相关性分析的工具,并不适合跨独立样本组的对比场景。

正确做法

根据你后续的可视化代码(取对角线相关性值),推测你要么想查看同一细胞类型在两组样本中的得分相关性,要么更可能是想对比两组样本中各细胞类型的得分差异,以下分别给出对应解决方案:

方案1:计算同一细胞类型在两组中的相关性(转置数据适配)

原始数据是「行=样本,列=细胞类型」,要计算两组中对应细胞类型的相关性,需要先转置数据,将细胞类型作为行、样本作为列:

# 转置数据,行是细胞类型,列是样本
cesc_transposed <- t(cesc_test)
hnsc_transposed <- t(hnsc_pos_test)

# 计算两组细胞类型得分的相关性矩阵
Cor <- corr.test(cesc_transposed, hnsc_transposed, adjust='none')

# 取对应细胞类型的相关性值(对角线)并可视化
qplot(x=rownames(Cor$r), y=diag(Cor$r),
      fill=diag(Cor$p)<0.05, geom='col',
      main='HPV+ HNSC vs HPV+ CESC',
      ylab='Pearson R', xlab= "") + 
  labs(fill = "p-value<0.05") +
  theme_classic() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

方案2:对比两组样本中各细胞类型的得分差异(更符合研究逻辑)

如果你的真实需求是看两组样本中细胞类型得分的差异(比如某细胞类型在头颈癌样本中是否显著更高),应该用差异检验(如Wilcoxon秩和检验,适配非正态分布的xCell得分数据):

library(tidyverse)

# 将宽格式数据转为长格式,方便分组分析
cesc_df <- cesc_test %>% 
  rownames_to_column("sample_id") %>% 
  pivot_longer(-sample_id, names_to = "cell_type", values_to = "score") %>% 
  mutate(group = "HPV+ CESC")

hnsc_df <- hnsc_pos_test %>% 
  rownames_to_column("sample_id") %>% 
  pivot_longer(-sample_id, names_to = "cell_type", values_to = "score") %>% 
  mutate(group = "HPV+ HNSC")

all_data <- bind_rows(cesc_df, hnsc_df)

# 对每个细胞类型做差异检验,并校正p值
diff_results <- all_data %>% 
  group_by(cell_type) %>% 
  summarise(
    p_value = wilcox.test(score ~ group)$p.value,
    p_adj = p.adjust(p_value, method = "fdr")
  )

# 可视化两组细胞类型得分的分布差异
ggplot(all_data, aes(x = cell_type, y = score, fill = group)) +
  geom_boxplot(width = 0.7) +
  theme_classic() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
  labs(
    title = "xCell Scores: HPV+ HNSC vs HPV+ CESC",
    x = "Cell Type", y = "xCell Score", fill = "Group"
  )

内容的提问来源于stack exchange,提问作者Kev Kev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 11:05:29