Skip to content

Commit

Permalink
Simplify tidyr::separate.soma_adat() S3 method
Browse files Browse the repository at this point in the history
- simplified code using `%||%`
- added expeanded error messages inside `stopifnot()`
- minor fix of unit test syntax
- fixes #72
  • Loading branch information
stufield committed Jan 5, 2024
1 parent 9c63813 commit 50e8a42
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 9 deletions.
11 changes: 5 additions & 6 deletions R/tidyr-verbs.R
Original file line number Diff line number Diff line change
Expand Up @@ -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, ...)
Expand Down
6 changes: 3 additions & 3 deletions tests/testthat/test-tidyr-verbs.R
Original file line number Diff line number Diff line change
@@ -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)

Expand All @@ -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))
Expand All @@ -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))
Expand Down

0 comments on commit 50e8a42

Please sign in to comment.