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

R语言:嵌套列表子集提取及带区分列的数据框合并

R嵌套列表处理方案

需求说明

  • 从嵌套列表的每个子列表中提取前3个元素(也可按指定名称提取,例如:c("hm", "ht", "cpht"))
  • 将每个子列表合并为数据框,并添加用于区分的标识列(参考最终结果)

示例数据

df1 <- data.frame(
  gene = c("a", "b", "c"),
  mutation = c("x", "y", "z"))

list1 <- list(
  hm = df1,
  ht = df1,
  cpht = df1,
  panel = df1)

list_o_lists <- list(
  pt1 = list1,
  pt2 = list1,
  pt3 = list1)

预期结果1

list_desired <- list(
  hm = df1,
  ht = df1,
  cpht = df1)

list_o_lists_desired <- list(
  pt1 = list_desired,
  pt2 = list_desired,
  pt3 = list_desired)

需求1的解决方案

使用purrr包的map()函数遍历嵌套列表,可通过两种方式提取目标元素:

  • 按索引提取前3个元素:
library(purrr)
list_o_lists_desired <- map(list_o_lists, ~ .x[1:3])
  • 按指定名称提取:
target_names <- c("hm", "ht", "cpht")
list_o_lists_desired <- map(list_o_lists, ~ .x[target_names])

需求2的解决方案

(注:编写示例时已找到对应方案)
先将每个子列表合并为带有type标识列的数据框,再整体合并添加pt标识列:

lol_final <- map(list_o_lists_desired, bind_rows, .id = "type")
df_final <- bind_rows(lol_final, .id = "pt")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 11:35:21