Thanks, I appreciate the pointers, but what I am interested in is why a column cannot be added to an empty tibble.
It may be due to an oversight in the implementation or maybe it is deliberate and there is something about the use of tibble::add_column I don't understand. Maybe the documentation needs to be updated (for completeness), there is nowhere it mentions that you cannot add_column to an empty tibble.
My example was an abstraction of what I am trying to do to keep the example as simple as possible. The actual task I'm trying to do is more involved than just adding a column to a tibble... maybe because I am looking at it the wrong way
... and for the moment building a tibble by adding one column at a time simplifies things.
But I've bumped into a function that does not seem to behave in the way that either it's name or it's documentation implies so I would like to find out if it is just an unimportant detail or something that needs to be fixed or documented.
Nick, I do know the number of rows that will be in the tibble before I create it.
FlorianGB . The error says that n > 0 is not true.
t1 <- tibble::tibble()
t2 <- tibble::add_column(t1, c1 = c(1,2,3))
#> Error: n > 0 is not TRUE
If I add_column was expecting 0 rows to be added I would expect something like
Error: .data
must have 0 rows, not 3
and adding a column with no rows in it produces a different error.
t1 <- tibble::tibble()
t2 <- tibble::add_column(t1, c1 = c())
#> Error: Column c1
must be a 1d atomic vector or a list
Here is an expanded example of what I am trying to do, again abstracted to keep the code as simple as a possible.
tib_example1 does not work because it tries to add a column to an empty tibble
tib_example2 works as expected but it requires the tibble to be initialized with a dummy column.
tib_example1 <- function(l) {
e <- environment()
e$tib <- tibble::tibble()
purrr::walk(l, function(c, e) {
e$tib <- tibble::add_column(e$tib, c)
}, e)
return(e$tib)
}
tib_example2 <- function(l) {
e <- environment()
e$tib <- tibble::tibble(1:3)
purrr::walk(l, function(c, e) {
e$tib <- tibble::add_column(e$tib, c)
}, e)
return(e$tib)
}
tib_example1(list(4:6))
#> Error: n > 0 is not TRUE
tib_example2(list(4:6))
#> # A tibble: 3 x 2
#> 1:3
c
#>
#> 1 1 4
#> 2 2 5
#> 3 3 6
Thanks again,
Dan