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

如何用gene与sample两列数据生成基因-样本存在缺失矩阵

解决方法

下面提供几种在R里实现需求的常用方式,都是针对把长格式的基因-样本对应表转换成宽格式存在/缺失矩阵的场景:

方法1:使用tidyverse(dplyr + tidyr)

这是现在R里最常用的tidy风格处理方式,代码可读性高:

# 先加载包
library(tidyverse)

# 转换格式
result_df <- df %>%
  mutate(value = 1) %>%  # 给每一行标记为1,表示基因在该样本中存在
  pivot_wider(names_from = sample,  # 把sample列的内容作为新列名
              values_from = value,  # 用value列的内容填充对应位置
              values_fill = 0)  # 基因未出现的样本位置填充0

如果数据里同一个基因在同一样本中可能重复出现,可添加values_fn = length确保计数(不过你的需求只要存在就标记1,现有代码已足够)。

方法2:使用base R的table函数

无需额外安装包,直接用基础函数快速处理:

# 生成列联表,自动统计每个基因在每个样本中的出现次数
gene_sample_table <- table(df$gene, df$sample)

# 把列联表转为数据框(需要矩阵的话直接用as.matrix(gene_sample_table))
result_df <- as.data.frame.matrix(gene_sample_table)

# 把计数大于0的统一改为1(若数据中基因-样本对唯一,此步可省略)
result_df[result_df > 0] <- 1

这个方法输出的结果直接是行为基因、列为样本的0/1矩阵,适配你的需求。

方法3:使用reshape2包的dcast

这是经典的宽格式转换工具,适合习惯reshape系列包的用户:

library(reshape2)

result_df <- dcast(df, gene ~ sample,  # 指定行是gene,列是sample
                   fun.aggregate = length,  # 统计基因在样本中的出现次数
                   value.var = "sample",  # 用于统计的目标列
                   fill = 0)  # 缺失位置填充0

# 将计数转为0/1格式
result_df[,-1][result_df[,-1] > 0] <- 1

用你提供的示例数据测试,以上方法都会输出符合要求的结果,比如:

sample-320 sample-359 sample-594 sample-326 sample-345 sample-346 sample-349 sample-350 sample-362 sample-363 sample-368 sample-369
rtxA         1          1          1          0          0          0          0          0          0          0          0          0
vibF         0          0          0          1          1          1          1          1          1          1          1          1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 02:57:31