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

在R中提取唯一基因并按A/B分组标注归属类别

需求

我有如下R语言数据框deg:

summary(deg)
      L2FC            Gene                    diffexp    comp   
 Min.   :-3.825   Length:926         Downregulated:210   A:195  
 1st Qu.: 1.010   Class :character   Upregulated  :716   B:731  
 Median : 1.163   Mode  :character                              
 Mean   : 0.860                                                 
 3rd Qu.: 1.431                                                 
 Max.   : 6.505    

head(deg)
       L2FC    Gene       diffexp comp
1 -2.754236 SLC13A2 Downregulated    A
2  3.161623   SNAI2   Upregulated    A
3 -2.821350   STYK1 Downregulated    A
4 -1.798022    CD84 Downregulated    A
5 -1.293536    TLE6 Downregulated    A
6 -1.011016   P2RX1 Downregulated    A

需要提取唯一的Gene符号,并按以下规则标注所属分组:

  • 1:仅属于分组A
  • -1:仅属于分组B
  • 0:同时属于A和B两组

期望输出格式如下:

Gene comp
1 GENE1    1
2 GENE2    0
3 GENE3   -1
解决方案

方法一:用dplyr包实现

library(dplyr)

result <- deg %>%
  group_by(Gene) %>%
  summarise(
    comp = case_when(
      all(comp == "A") ~ 1,
      all(comp == "B") ~ -1,
      TRUE ~ 0
    ),
    .groups = "drop"
  )

# 查看结果
head(result)

方法二:基础R实现(无需额外包)

# 按Gene分组,获取每个基因对应的唯一分组
gene_comps <- tapply(deg$comp, deg$Gene, unique)

# 根据分组情况生成标注值
comp_labels <- sapply(gene_comps, function(x) {
  if (length(x) == 1) {
    if (x == "A") 1 else -1
  } else {
    0
  }
})

# 转换为目标数据框
result <- data.frame(
  Gene = names(comp_labels),
  comp = as.integer(comp_labels),
  row.names = NULL
)

# 查看结果
head(result)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 23:58:21