Initialize an empty tibble with column names and 0 rows

colorlace picture colorlace · Feb 16, 2018 · Viewed 29.9k times · Source

I have a vector of column names called tbl_colnames.

I would like to create a tibble with 0 rows and length(tbl_colnames) columns.

The best way I've found of doing this is...

tbl <- as_tibble(data.frame(matrix(nrow=0,ncol=length(tbl_colnames)))

and then I want to name the columns so...

colnames(tbl) <- tbl_colnames.

My question: Is there a more elegant way of doing this?

something like tbl <- tibble(colnames=tbl_colnames)

Answer

Daniel picture Daniel · Aug 31, 2019
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.