使用表名向量在R中合并多个表格。

huangapple go评论126阅读模式
英文:

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 &lt;- tibble(col_1 = c(1,2), col_2 = c(&quot;a1&quot;, &quot;a2&quot;))
B_table &lt;- tibble(col_1 = c(1,4), col_2 = c(&quot;b11&quot;, &quot;b3&quot;))
C_table &lt;- tibble(col_1 = c(5,9), col_2 = c(&quot;c21&quot;, &quot;c2&quot;))

tables &lt;- ls(pat = &quot;_table&quot;)                  

#doesnt work:
combine &lt;- tables %&gt;% 
  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 &lt;- A_table %&gt;% 
    bind_rows(B_table) %&gt;% 
    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 &#215; 2
#   col_1 col_2
#   &lt;dbl&gt; &lt;chr&gt;
# 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))
#&gt; # 一个 tibble: 6 &#215; 2
#&gt;   col_1 col_2
#&gt; * &lt;dbl&gt; &lt;chr&gt;
#&gt; 1     1 a1   
#&gt; 2     2 a2   
#&gt; 3     1 b11  
#&gt; 4     4 b3   
#&gt; 5     5 c21  
#&gt; 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))
#&gt; # A tibble: 6 &#215; 2
#&gt;   col_1 col_2
#&gt; * &lt;dbl&gt; &lt;chr&gt;
#&gt; 1     1 a1   
#&gt; 2     2 a2   
#&gt; 3     1 b11  
#&gt; 4     4 b3   
#&gt; 5     5 c21  
#&gt; 6     9 c2

<sup>Created on 2023-06-05 with reprex v2.0.2</sup>

huangapple
  • 本文由 发表于 2023年6月5日 21:23:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/76406871.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定