英文:
Combine multiple tables in R using a vector of table names
问题
我有三个数据集(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只是一个包含表名的列表,而不是实际的表格。
有什么简单的方法可以合并这三个表格?
如何使用模式获取变量tables中的表格,而不仅仅是表格名称?
我不想手动绑定它们,例如:
combine <- A_table %>%
bind_rows(B_table) %>%
bind_rows(C_table)
因为我有更多的列要合并。
我感激任何建议!谢谢!
英文:
I have three datasets (tibble), all with the same column names
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")
#doesnt work:
combine <- tables %>%
reduce(bind_rows)
The combine doesn't work because tables is just a list with the table names, not with the real tables.
What is an easy way to combine the three tables?
How do I get the tables in the variable tables and not only the table names using a pattern?
I don't want to bind them manually, e.g.:
combine <- A_table %>%
bind_rows(B_table) %>%
bind_rows(C_table)
because in I have many more columns that I want to combine.
I appreciate any advise! Thank you!
答案1
得分: 5
使用 mget
+ bind_rows
:
bind_rows(mget(tables))
# # 一个 tibble: 6 × 2
# col_1 col_2
# <dbl> <chr>
# 1 1 a1
# 2 2 a2
# 3 1 b11
# 4 4 b3
# 5 5 c21
# 6 9 c2
英文:
With mget
+ bind_rows
:
bind_rows(mget(tables))
# # A tibble: 6 × 2
# col_1 col_2
# <dbl> <chr>
# 1 1 a1
# 2 2 a2
# 3 1 b11
# 4 4 b3
# 5 5 c21
# 6 9 c2
答案2
得分: 2
另一个选项可能是使用`do.call`与`rbind`和`mget`,如下所示:
```r
do.call(rbind, mget(tables))
#> # 一个 tibble: 6 × 2
#> col_1 col_2
#> * <dbl> <chr>
#> 1 1 a1
#> 2 2 a2
#> 3 1 b11
#> 4 4 b3
#> 5 5 c21
#> 6 9 c2
<sup>创建于 2023-06-05,使用 reprex v2.0.2</sup>
<details>
<summary>英文:</summary>
Another option could be using `do.call` with `rbind` and `mget` like this:
``` r
do.call(rbind, mget(tables))
#> # A tibble: 6 × 2
#> col_1 col_2
#> * <dbl> <chr>
#> 1 1 a1
#> 2 2 a2
#> 3 1 b11
#> 4 4 b3
#> 5 5 c21
#> 6 9 c2
<sup>Created on 2023-06-05 with reprex v2.0.2</sup>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论