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

在R中如何通过表名向量批量合并多个同结构tibble?

批量合并列名一致的tibble数据集

我拥有三个列名完全相同的tibble数据集,代码如下:

A_table <- tibble(col_1 = c(1,2), col_2 = c("a1", "a2"))
B_table <- tibble(col_1 = c(1,4), col_2 = c("b11", "b3"))
C_table <- tibble(col_1 = c(5,9), col_2 = c("c21", "c2"))

tables <- ls(pat = "_table")                  

#无法运行:
combine <- tables %>% 
  reduce(bind_rows)

上述合并代码无法运行,因为tables仅为存储表名的向量,而非实际的表对象。请问:如何简便地合并这三个表?如何通过匹配模式获取实际的表对象而非仅表名?我不想手动逐个绑定(如以下示例),因为实际需要合并的表数量更多:

combine <- A_table %>% 
  bind_rows(B_table) %>% 
  bind_rows(C_table)

解决方案

方法1:用mget()批量获取表对象并合并

mget()可根据字符向量中的名称从当前环境提取对应对象,返回一个包含所有目标表的列表,随后直接用bind_rows()完成合并:

library(dplyr)

# 获取所有匹配"_table"后缀的表对象
tables_list <- mget(ls(pat = "_table"))

# 合并列表内的所有tibble
combine <- bind_rows(tables_list)

方法2:tidyverse管道风格实现

借助purrr::map()遍历表名字符向量,用get()取出每个表对象,再通过bind_rows()合并:

library(dplyr)
library(purrr)

combine <- ls(pat = "_table") %>%
  map(get) %>%  # 逐个提取表对象
  bind_rows()   # 批量合并所有表(用reduce(bind_rows)效果一致)

关键说明

  • 确保所有匹配模式的表列名完全一致,否则合并会报错或产生异常结果;
  • 若表存储在自定义环境中,需在mget()或get()中指定envir参数,例如mget(ls(pat = "_table"), envir = my_custom_env)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 14:40:13