Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize an empty tibble with column names and 0 rows

Tags:

r

tibble

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)

like image 706
colorlace Avatar asked Feb 16 '18 19:02

colorlace


People also ask

How do you create an empty DataFrame in R with column names?

To create an empty data frame with column names , initialize a vector with column names first, c() is used to create a Vector in R. And then create DataFrame by using data. frame() function and assign this vector to columns(df) .

How do I create a new Tibble in R?

You can create a new tibble from individual vectors with tibble() . tibble() will automatically recycle inputs of length 1, and allows you to refer to variables that you just created, as shown below.

What does Tibble :: Enframe () do?

See Also tibble() constructs a tibble from individual columns. enframe() converts a named vector to a tib- ble with a column of names and column of values.

Can Tibbles create row names?

While a tibble can have row names (e.g., when converting from a regular data frame), they are removed when subsetting with the [ operator. A warning will be raised when attempting to assign non- NULL row names to a tibble.


2 Answers

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.

like image 97
Daniel Avatar answered Sep 29 '22 20:09

Daniel


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 
like image 42
Tony416 Avatar answered Sep 29 '22 20:09

Tony416