diff --git a/R/flatten.R b/R/flatten.R index 1e7082f3e8..0badfcd2ae 100644 --- a/R/flatten.R +++ b/R/flatten.R @@ -36,10 +36,16 @@ list_flatten <- function(x, ..., ptype = x, name_spec = NULL) { ellipsis::check_dots_empty() list_assert(x) - # Wrap any non-list elements - out <- map_if(x, negate(vec_is_list), list) + if (vec_is_list(ptype)) { + # Wrap any non-list elements so all the elements to concatenate are lists + out <- map_if(x, negate(vec_is_list), list) + } else { + # Unchop all list elements so all the elements to concatenate are of type `ptype` + out <- map_if(x, vec_is_list, vec_unchop, ptype = ptype, name_spec = name_spec) + } - # Concatenate the elements (now all lists) in a single list + # Concatenate the elements (now all lists or all vectors) in a + # vector of type `ptype` vec_unchop(out, ptype = ptype, name_spec = name_spec) } diff --git a/tests/testthat/test-flatten.R b/tests/testthat/test-flatten.R index 7385bb17c2..a17761769e 100644 --- a/tests/testthat/test-flatten.R +++ b/tests/testthat/test-flatten.R @@ -35,3 +35,18 @@ test_that("list_flatten() creates output of type `ptype`", { new_count_list(list(1, 2)) ) }) + +test_that("list_flatten() creates atomic vectors if requested", { + expect_identical( + list_flatten(list(1, list(2)), ptype = int()), + 1:2 + ) + expect_identical( + list_flatten( + list(x = 1, y = list(foo = 2)), + ptype = int(), + name_spec = "{outer}_{inner}" + ), + c(x = 1L, y_foo = 2L) + ) +})