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

在R中整合两个列表:统计单倍型计数及对应ls总和求助

R语言:整合单倍型列表与对应元数据

需求说明

现有两个长度匹配的列表:

  • haps:每个元素对应一个窗口的单倍型编码向量(共1-6号窗口)
  • ls:每个元素对应同一窗口的元数据向量,位置与haps完全一一对应(如haps[[1]][1]对应ls[[1]][1])

需要为每个窗口生成包含以下字段的结果表:

  • haplotype:单倍型编码
  • count:该单倍型在窗口内的出现次数
  • ls:该单倍型对应所有元数据的总和

示例数据

haps 列表内容

`1`
[1] 19 31 31 31 31

$`2`
[1]  7 31 31 31 31

$`3`
[1] 15 31 31 31 31

$`4`
[1] 31 31 31 31 31

$`5`
[1] 31 31 31 31 31

$`6`
[1] 30 31 31 31 31

ls 列表内容

$`1`
[1] 2 0 2 3 4

$`2`
[1] 2 0 2 3 4

$`3`
[1] 2 0 2 3 4

$`4`
[1] 2 0 2 3 4

$`5`
[1] 2 0 2 3 4

$`6`
[1] 2 0 2 3 4

期望输出

每个窗口对应一个数据框,示例如下:

$`1`
  haplotype count ls
1        19     1   2
2        31     4   9

$`2`
  haplotype count ls
1         7     1   2
2        31     4   9

$`3`
  haplotype count ls
1        15     1   2
2        31     4   9

$`4`
  haplotype count ls
1        31     5   11

$`5`
  haplotype count ls
1        31     5   11

$`6`
  haplotype count ls
1        30     1   2
2        31     4   9

现有代码(未完成)

已实现单倍型计数,但无法计算对应元数据总和:

counting <- function(x,y) {
  u <- unique(x);
  data.frame(
    haplotype=u,
    count=sapply(u, function(v) { length(which(x==v)) } )
  )
}

counts = lapply(haps, counting)

解决方案

方案1:修改原自定义函数

调整counting函数,新增元数据求和逻辑,同时改用mapply遍历两个列表:

counting <- function(x, y) {
  u <- unique(x)
  data.frame(
    haplotype = u,
    count = sapply(u, function(v) sum(x == v)),  # 简化计数写法,替代length(which(...))
    ls = sapply(u, function(v) sum(y[x == v]))
  )
}

# 用mapply同时传递haps和ls的对应元素,SIMPLIFY=FALSE确保输出为列表
counts <- mapply(counting, haps, ls, SIMPLIFY = FALSE)

方案2:使用tidyverse工具链(更直观)

借助purrr和dplyr的语法,逻辑更清晰:

library(tidyverse)

# 定义单个窗口的处理函数
process_window <- function(hap_vec, ls_vec) {
  tibble(haplotype = hap_vec, ls = ls_vec) %>%
    group_by(haplotype) %>%
    summarise(
      count = n(),
      ls = sum(ls),
      .groups = "drop"
    )
}

# 用map2遍历两个列表生成结果
counts <- map2(haps, ls, process_window)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 04:18:14