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

在R语言中按名称合并列表中指定的data.frame元素

解决R语言列表中指定命名data.frame的合并问题

要实现将列表中指定名称的data.frame合并为带来源标识的单个data.frame,核心是先关联每个子data.frame对应的列表名称,再进行合并,以下是两种可行方案:

基础R实现

步骤1:提取指定元素

先从列表中筛选出需要合并的"m"和"o"对应的data.frame:

selected <- lst[c("m", "o")]

步骤2:关联列表名称与子data.frame

通过Map函数为每个子data.frame设置对应名称的行名(重复次数为该data.frame的行数):

selected <- Map(function(df, nm) {
  rownames(df) <- rep(nm, nrow(df))
  df
}, selected, names(selected))

步骤3:合并为单个data.frame

用do.call(rbind, ...)完成合并:

result <- do.call(rbind, selected)

执行后即可得到你期望的格式输出。

tidyverse工具包实现(更简洁)

如果习惯使用tidyverse生态,代码会更简洁直观,同时推荐保留来源标识列而非仅依赖行名(便于后续数据处理):

library(tidyverse)

# 提取指定元素→添加来源列→合并
result <- lst %>%
  pluck(c("m", "o")) %>%
  imap(~ mutate(.x, source = .y)) %>%
  bind_rows()

# 若需要将source列转为行名(匹配你的示例格式),可执行:
result <- result %>% column_to_rownames(var = "source")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 17:21:05