Initialize an empty tibble with column names and 0 rows

my_tibble <- tibble(
  var_name_1 = numeric(),
  var_name_2 = numeric(),
  var_name_3 = numeric(),
  var_name_4 = numeric(),
  var_name_5 = numeric()
)

Haven't tried, but I guess it works too if instead of initiating numeric vectors of length 0 you do it with other classes (for example, character()).

This SO question explains how to do it with other R libraries.

According to this tidyverse issue, this won't be a feature for tribbles.


Since you want to combine a list of tibbles. You can just assign NULL to the variable and then bind_rows with other tibbles.

res = NULL
for(i in tibbleList)
   res = bind_rows(res,i)

However, a much efficient way to do this is

bind_rows(tibbleList) # combine all tibbles in the list

For anyone still interested in an elegant way to create a 0-row tibble with column names given by a character vector tbl_colnames:

tbl_colnames %>% purrr::map_dfc(setNames, object = list(logical()))

or:

tbl_colnames %>% purrr::map_dfc(~tibble::tibble(!!.x := logical()))

or:

tbl_colnames %>% rlang::rep_named(list(logical())) %>% tibble::as_tibble()

This, of course, results in each column being of type logical.

Tags:

R

Tibble