Bind tibbles

Tibbles can be bound together to create a new tibble with:

Tidyverse reference page

Create example tibbles

Before demonstrating various examples we will create a few tibbles.

num_tbl <- tibble::tibble(x = 1:3, y = 4:6, z = 7:9)
num_tbl_2 <- tibble::tibble(aa = 11:13, ab = 14:16, ac = 17:19)
num_tbl_3 <- tibble::tibble(x = 4:6, y = 7:9, z = 10:12)

Bind by columns

Bind 2 or more tibbles by columns. In other words you will end up with more columns and the same amount of rows.

We will bind the two following tibbles by columns.

Note that the two tibbles must have the same amount of rows. Additionally, they should have completely unique column names compared to each other.

num_tbl
# A tibble: 3 × 3
      x     y     z
  <int> <int> <int>
1     1     4     7
2     2     5     8
3     3     6     9
num_tbl_2
# A tibble: 3 × 3
     aa    ab    ac
  <int> <int> <int>
1    11    14    17
2    12    15    18
3    13    16    19

Column bind

num_tbl_col_bound <- dplyr::bind_cols(num_tbl, num_tbl_2)
num_tbl_col_bound
# A tibble: 3 × 6
      x     y     z    aa    ab    ac
  <int> <int> <int> <int> <int> <int>
1     1     4     7    11    14    17
2     2     5     8    12    15    18
3     3     6     9    13    16    19

Bind by rows

Bind 2 or more tibbles by rows with dplyr::bind_rows(). In other words you will end up with more rows and the same amount of columns.

We will bind the two following tibbles by rows.

Note that the two tibbles must have the same amount of columns. Additionally, they should have the same column names.

num_tbl
# A tibble: 3 × 3
      x     y     z
  <int> <int> <int>
1     1     4     7
2     2     5     8
3     3     6     9
num_tbl_3
# A tibble: 3 × 3
      x     y     z
  <int> <int> <int>
1     4     7    10
2     5     8    11
3     6     9    12

Row bind

num_tbl_row_bound <- dplyr::bind_rows(num_tbl, num_tbl_3)
num_tbl_row_bound
# A tibble: 6 × 3
      x     y     z
  <int> <int> <int>
1     1     4     7
2     2     5     8
3     3     6     9
4     4     7    10
5     5     8    11
6     6     9    12