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)
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) .
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With