From aff36c2bbb89f7954717238ba6312bc26f506438 Mon Sep 17 00:00:00 2001 From: Jon Harmon Date: Fri, 23 Feb 2024 11:14:26 -0600 Subject: [PATCH] Flatten lists when possible. (#68) Only for chr right now. Will need to refactor and generalize this. --- DESCRIPTION | 4 ++-- NAMESPACE | 2 ++ R/to_chr.R | 7 +++++++ tests/testthat/test-to_chr.R | 15 +++++++++++++++ 4 files changed, 26 insertions(+), 2 deletions(-) diff --git a/DESCRIPTION b/DESCRIPTION index 8d18261..9655d0d 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,6 +1,6 @@ Package: stbl Title: Stabilize Function Arguments -Version: 0.0.0.9000 +Version: 0.0.0.9001 Authors@R: person("Jon", "Harmon", , "jonthegeek@gmail.com", role = c("aut", "cre"), comment = c(ORCID = "0000-0003-4781-4346")) @@ -24,4 +24,4 @@ Config/testthat/edition: 3 Config/testthat/parallel: true Encoding: UTF-8 Roxygen: list(markdown = TRUE) -RoxygenNote: 7.2.3 +RoxygenNote: 7.3.0 diff --git a/NAMESPACE b/NAMESPACE index 04f34b4..386f94a 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -7,8 +7,10 @@ S3method(to_chr,default) S3method(to_chr,list) S3method(to_fct,"NULL") S3method(to_fct,character) +S3method(to_fct,data.frame) S3method(to_fct,default) S3method(to_fct,factor) +S3method(to_fct,list) S3method(to_int,"NULL") S3method(to_int,character) S3method(to_int,complex) diff --git a/R/to_chr.R b/R/to_chr.R index 8074cbe..bfa1bce 100644 --- a/R/to_chr.R +++ b/R/to_chr.R @@ -52,6 +52,13 @@ to_chr.list <- function(x, x_arg = caller_arg(x), call = caller_env(), x_class = object_type(x)) { + flat <- unlist(x) + if (length(flat) == length(x)) { + if (length(flat) == 1) { + flat <- flat[[1]] + } + return(to_chr(flat)) + } .stop_cant_coerce( from_class = x_class, to_class = "character", diff --git a/tests/testthat/test-to_chr.R b/tests/testthat/test-to_chr.R index 22b8ec1..fb1d6f4 100644 --- a/tests/testthat/test-to_chr.R +++ b/tests/testthat/test-to_chr.R @@ -68,6 +68,21 @@ test_that("to_chr() works for other things", { ) }) +test_that("to_chr() tries to flatten lists", { + expect_identical( + to_chr(list("a", "b")), + c("a", "b") + ) + expect_identical( + to_chr(list(1, 2)), + c("1", "2") + ) + expect_identical( + to_chr(list("a")), + c("a") + ) +}) + test_that("to_chr() fails gracefully for weird cases", { wrapper <- function(wrapper_val, ...) { return(to_chr(wrapper_val, ...))