From 53e89c87c3e28a99335318a922d5afcd0278b664 Mon Sep 17 00:00:00 2001 From: Etienne Bacher <52219252+etiennebacher@users.noreply.github.com> Date: Thu, 8 Aug 2024 14:13:27 +0200 Subject: [PATCH] feat: `as_polars_df()` keeps the schema when converting a `nanoarrow_array` with 0 rows --- NEWS.md | 2 ++ R/as_polars.R | 8 +------- tests/testthat/test-as_polars.R | 11 +++++++++++ 3 files changed, 14 insertions(+), 7 deletions(-) diff --git a/NEWS.md b/NEWS.md index fc887bd8e..fa58664bf 100644 --- a/NEWS.md +++ b/NEWS.md @@ -5,6 +5,8 @@ ### New features - New method `$str$extract_many()` (#1163). +- Converting a `nanoarrow_array` with zero rows to an `RPolarsDataFrame` via + `as_polars_df()` now keeps the original schema (#1177). ### Bug fixes diff --git a/R/as_polars.R b/R/as_polars.R index a75232b2a..4d7279433 100644 --- a/R/as_polars.R +++ b/R/as_polars.R @@ -257,13 +257,7 @@ as_polars_df.nanoarrow_array = function(x, ...) { } series = as_polars_series.nanoarrow_array(x, name = NULL) - - if (length(series)) { - series$to_frame()$unnest("") - } else { - # TODO: support 0-length array - pl$DataFrame() - } + series$to_frame()$unnest("") } diff --git a/tests/testthat/test-as_polars.R b/tests/testthat/test-as_polars.R index 3c04f46a5..c84c65311 100644 --- a/tests/testthat/test-as_polars.R +++ b/tests/testthat/test-as_polars.R @@ -513,3 +513,14 @@ patrick::with_parameters_test_that( }, .cases = make_as_polars_df_experimental_cases() ) + + +test_that("as_polars_df works for nanoarrow_array with zero rows", { + skip_if_not_installed("nanoarrow") + orig = data.frame(col1 = character(0), col2 = numeric(0)) + out = nanoarrow::as_nanoarrow_array(orig) |> + as_polars_df() |> + as.data.frame() + expect_identical(out, orig) + expect_identical(lapply(out, class), list(col1 = "character", col2 = "numeric")) +})