From 6520dc0d11b4cc320c29edb61f3a891404585a1f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kim=20L=C3=B3pez=20G=C3=BCell?= <99121045+KimLopezGuell@users.noreply.github.com> Date: Tue, 20 Aug 2024 21:50:26 +0100 Subject: [PATCH] Allow `list_transpose()` to work on data frames (#1141) Fixes #1109 --------- Co-authored-by: Hadley Wickham --- NEWS.md | 1 + R/list-transpose.R | 3 ++- tests/testthat/_snaps/list-transpose.md | 2 +- tests/testthat/test-list-transpose.R | 6 ++++++ 4 files changed, 10 insertions(+), 2 deletions(-) diff --git a/NEWS.md b/NEWS.md index eb5dc4c6..5d5177af 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,6 @@ # purrr (development version) +* `list_transpose()` now works with data.frames (@KimLopezGuell, #1109). * Added `imap_vec()` (#1084) * `list_transpose()` inspects all elements to determine the correct template if it's not provided by the user (#1128, @krlmlr). diff --git a/R/list-transpose.R b/R/list-transpose.R index cd9e737d..a3dba5b2 100644 --- a/R/list-transpose.R +++ b/R/list-transpose.R @@ -69,7 +69,8 @@ list_transpose <- function(x, simplify = NA, ptype = NULL, default = NULL) { - vec_check_list(x) + + check_list(x) check_dots_empty() if (length(x) == 0) { diff --git a/tests/testthat/_snaps/list-transpose.md b/tests/testthat/_snaps/list-transpose.md index 36a7dd4d..10ccbc6d 100644 --- a/tests/testthat/_snaps/list-transpose.md +++ b/tests/testthat/_snaps/list-transpose.md @@ -57,7 +57,7 @@ list_transpose(10) Condition Error in `list_transpose()`: - ! `x` must be a list, not the number 10. + ! `x` must be a list, not a number. Code list_transpose(list(1), template = mean) Condition diff --git a/tests/testthat/test-list-transpose.R b/tests/testthat/test-list-transpose.R index 91895abf..872e5b7f 100644 --- a/tests/testthat/test-list-transpose.R +++ b/tests/testthat/test-list-transpose.R @@ -4,6 +4,12 @@ test_that("can transpose homogenous list", { expect_equal(out, list(a = c(x = 1, y = 3), b = c(x = 2, y = 4))) }) +test_that("can transpose data frames", { + df <- data.frame(x = 1:2, y = 4:5) + out <- list_transpose(df) + expect_equal(out, list(c(x = 1, y = 4), c(x = 2, y = 5))) +}) + test_that("transposing empty list returns empty list", { expect_equal(list_transpose(list()), list()) })