Initialize an empty tibble with column names and 0 rows
Solution 1
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
Solution 2
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.
Solution 3
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.
Solution 4
You could abuse readr::read_csv
, which allow to read from string. You can control names and types, e.g.:
tbl_colnames <- c("one", "two", "three", "c4", "c5", "last")
read_csv("\n", col_names = tbl_colnames) # all character type
read_csv("\n", col_names = tbl_colnames, col_types = "lcniDT") # various types
![colorlace](https://i.stack.imgur.com/rGMaY.jpg?s=256&g=1)
colorlace
"Two fleeting powers I should wish to have at my command. The second, to be understood, and the first, to understand." -IG WordsForThat
Updated on August 26, 2020Comments
-
colorlace almost 4 years
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)
-
colorlace about 6 yearsThank you for your answer. It was a list of lists (not a list of tibbles), but this seems to work anyway!
-
colorlace almost 5 yearsThanks. I was hoping to use the
tbl_colnames
vector directly when I asked this question, but it's true that this is one way to do it (if a bit cumbersome). In any case, it could be helpful for others seeking different ways to init tibbles. -
Aren Cambre over 4 yearsThis answer is responsive to a comment that is only peripherally related the title of and question posted on this page.