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

如何拆分含非统一分隔符的列表元素?基因名后缀处理问询

处理基因名后缀的dplyr方案问题

问题场景

分析生成的表格以基因为行名,部分基因名被自动添加.#后缀(如.1、.2)以保证唯一性,示例行名片段:

c("Cck", "Pcp4.3", "Adcy1.4", "Cpe.3", "Dsp.5", "Dgkh.4", "Ncdn.4", "Marcksl1.3","Fam163b.5","Stxbp6.3","Prox1.3", "Neurod6.3", "Dock10.2","Fth1.3","Ipcef1","Pgbd5.3","Sema5a.2","Ahcyl2.2","Hpca.3","Gpr151")

需要移除这些后缀,同时验证推测:后缀数值 = 该基因出现次数 - 1。

尝试的代码及错误

使用separate_wider_delim拆分时出现报错:

df %>% 
  rownames_to_column(var = "Gene.ID") %>% 
  separate_wider_delim(Gene.ID, delim = ".", names = c("Gene", "num")) 

错误信息:

Error in `separate_wider_delim()`:
! Expected 2 pieces in each element of `Gene.ID`.
! 3271 values were too short.
ℹ Use `too_few = "debug"` to diagnose the problem.
ℹ Use `too_few = "align_start"/"align_end"` to silence this message.
! 2 values were too long.
ℹ Use `too_many = "debug"` to diagnose the problem.
ℹ Use `too_many = "drop"/"merge"` to silence this message.
Backtrace:
 1. All_Markers %>% rownames_to_column(var = "Gene.ID") %>% ...
 2. tidyr::separate_wider_delim(., Gene.ID, delim = ".", names = c("Gene", "Occur"))

错误原因:部分基因名不含.(拆分后只有1段,触发too_few),少数基因名本身包含.(拆分后超过2段,触发too_many),不符合separate_wider_delim预设的拆分数量。

解决方案:正则表达式精准拆分

利用正则匹配末尾的.数字后缀,既能处理无后缀的基因,也能兼容基因名本身带.的情况:

library(dplyr)
library(tidyr)

# 拆分基因名和后缀
df_cleaned <- df %>%
  rownames_to_column(var = "Gene.ID") %>%
  # 匹配末尾的.数字,提取基因名和后缀;无后缀的num列填NA
  extract(
    Gene.ID,
    into = c("Gene", "num"),
    regex = "^(.*?)\\.(\\d+)$",
    fill = "right"
  ) %>%
  # 给无后缀的基因补充Gene值
  mutate(Gene = ifelse(is.na(num), Gene.ID, Gene))

验证后缀推测

统计每个基因的出现次数,对比后缀数值是否等于出现次数-1:

# 统计基因出现次数
gene_occurrences <- df_cleaned %>%
  count(Gene, name = "total_occurrences")

# 合并数据并验证
validation_result <- df_cleaned %>%
  left_join(gene_occurrences, by = "Gene") %>%
  mutate(
    num = as.integer(num),
    expected_suffix = total_occurrences - 1,
    # 无后缀的基因,预期出现次数为1
    is_match = ifelse(is.na(num), total_occurrences == 1, num == expected_suffix)
  )

# 查看匹配结果统计
table(validation_result$is_match)

# 查看不匹配的异常项(可选)
validation_result %>% filter(!is_match)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 16:23:12