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

如何基于另一DataFrame的区间匹配基因与突变信息(R语言)

问题描述

现有两个R DataFrame:

  • df1包含基因名称及其基因组位置区间(起始min、终止max):
df1 = data.frame("gene" = c("a","b","c"), "min" = c(1,3,5), "max"=c(2,4,6))
  • df2包含突变位置及影响程度:
df2 = data.frame("position" = c(1.5,3.5,5.5),"impact" = c("low","low","high"))

需要生成新的DataFrame,展示突变位置、所属基因及影响程度,期望输出:

position  gene     impact
1.5       a        low
3.5       b        low
5.5       c        high
解决方案

方法1:基础R实现

遍历每个突变位置,匹配对应基因区间:

# 为df2添加匹配到的基因列
df2$gene <- sapply(df2$position, function(x) df1$gene[df1$min <= x & df1$max >= x])
# 调整列顺序以匹配期望输出
result <- df2[, c("position", "gene", "impact")]
print(result)

方法2:dplyr包实现

通过交叉连接加过滤完成匹配,适合复杂场景扩展:

library(dplyr)

result <- df2 %>%
  cross_join(df1) %>%
  filter(position >= min & position <= max) %>%
  select(position, gene, impact)

print(result)

方法3:data.table包实现

非等连接效率更高,适合大规模数据处理:

library(data.table)

setDT(df1)
setDT(df2)

result <- df2[df1, on = .(position >= min, position <= max), 
              .(position = x.position, gene, impact)]

print(result)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 13:09:56