Adding rows and columns

Data can be added to a tibble by various methods. this includes:

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)
mixed_tbl <- tibble::tibble(number = 1:3, 
                            word = c("one","two","three"), 
                            logical = c(TRUE,FALSE,TRUE))

Adding one row or column

Adding one new column or row can be carried out with the

intuitively named functions:

Adding a column

We will add a column to the tibble num_tbl.

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

To add a new column you can provide tibble::add_column() with a vector that is the same length as the number of rows. In the below example the new column will have the name aa.

num_tbl_added_col <- tibble::add_column(num_tbl, aa = 10:12)
num_tbl_added_col
# A tibble: 3 × 4
      x     y     z    aa
  <int> <int> <int> <int>
1     1     4     7    10
2     2     5     8    11
3     3     6     9    12

Adding a row

We will add a row to the tibble mixed_tbl.

mixed_tbl
# A tibble: 3 × 3
  number word  logical
   <int> <chr> <lgl>  
1      1 one   TRUE   
2      2 two   FALSE  
3      3 three TRUE   

To add a row you can use tibble::add_row(). Each column of the tibble needs to be specified as an option with its added value. Each value must have the same class as the column it is being added to.

mixed_tbl_add_row <- tibble::add_row(mixed_tbl, 
                                    number = 4,  
                                    word = "four",  
                                    logical = FALSE)
mixed_tbl_add_row
# A tibble: 4 × 3
  number word  logical
   <dbl> <chr> <lgl>  
1      1 one   TRUE   
2      2 two   FALSE  
3      3 three TRUE   
4      4 four  FALSE  

Binding a tibble to a tibble

Tibbles can be bound together to create a new tibble with dplyr::bind_cols() and dplyr::bind_rows().

Please view the Dplyr bind tibbles page for examples.