From 50e8a42443353a276293b297d6894fe23bb00cab Mon Sep 17 00:00:00 2001 From: Stu Field Date: Fri, 5 Jan 2024 11:15:35 -0700 Subject: [PATCH] Simplify `tidyr::separate.soma_adat()` S3 method - simplified code using `%||%` - added expeanded error messages inside `stopifnot()` - minor fix of unit test syntax - fixes #72 --- R/tidyr-verbs.R | 11 +++++------ tests/testthat/test-tidyr-verbs.R | 6 +++--- 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/R/tidyr-verbs.R b/R/tidyr-verbs.R index b476c98..36445c4 100644 --- a/R/tidyr-verbs.R +++ b/R/tidyr-verbs.R @@ -9,13 +9,12 @@ separate.soma_adat <- function(data, col, into, sep = "[^[:alnum:]]+", fill = "warn", ...) { atts <- attributes(data) data <- rn2col(data, ".separate_rn") - # must do it this way b/c NextMethod() doesn't play nice with tidyeval - col2 <- tryCatch(col, error = function(e) NULL) # NULL if 'col' is lazyeval - if ( is.null(col2) ) col2 <- deparse(substitute(col)) + # must do it this way b/c NextMethod() doesn't play nice with lazyeval + col2 <- tryCatch(eval(col), error = function(e) NULL) %||% deparse(substitute(col)) stopifnot( - length(col2) == 1L, - is.character(col2), - col2 %in% names(data) + "`col` must be a `character(1)` or a symbol." = is.character(col2), + "`col` must have length = 1." = length(col2) == 1L, + "`col` must be a variable name in `data`." = col2 %in% names(data) ) data <- data.frame(data) .data <- tidyr::separate(data, col2, into, sep, remove, convert, extra, fill, ...) diff --git a/tests/testthat/test-tidyr-verbs.R b/tests/testthat/test-tidyr-verbs.R index 3566225..f511414 100644 --- a/tests/testthat/test-tidyr-verbs.R +++ b/tests/testthat/test-tidyr-verbs.R @@ -1,7 +1,7 @@ # Setup ---- data <- mock_adat() -data$a <- LETTERS[1:6] +data$a <- LETTERS[1:6L] data$d <- as.character(1:6) data$b <- paste0(data$a, "-", data$d) @@ -12,7 +12,7 @@ test_that("separate() method produces expected output", { expect_s3_class(new, "soma_adat") expect_true(is_intact_attr(new)) expect_equal(class(new), class(data)) - expect_equal(dim(new), dim(data) + c(0, 1)) # 1 new column + expect_equal(dim(new), dim(data) + c(0, 1L)) # 1 new column expect_true("c" %in% names(new)) expect_true("b" %in% names(new)) expect_equal(rownames(new), rownames(data)) @@ -36,7 +36,7 @@ test_that("unite() method produces expected output", { expect_s3_class(new, "soma_adat") expect_true(is_intact_attr(new)) expect_equal(class(new), class(data)) - expect_equal(dim(new), dim(data) + c(0, -1)) # 1 less column + expect_equal(dim(new), dim(data) + c(0, -1L)) # 1 less column expect_true("combo" %in% names(new)) expect_false("a" %in% names(new)) expect_false("d" %in% names(new))