diff --git a/DESCRIPTION b/DESCRIPTION index 7d1bc8e8e..b1a68f5c3 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,7 +1,7 @@ Type: Package Package: datawizard Title: Easy Data Wrangling and Statistical Transformations -Version: 0.7.1.12 +Version: 0.7.1.13 Authors@R: c( person("Indrajeet", "Patil", , "patilindrajeet.science@gmail.com", role = "aut", comment = c(ORCID = "0000-0003-1995-6531", Twitter = "@patilindrajeets")), diff --git a/R/data_modify.R b/R/data_modify.R index 8a899059d..8ff1f3a75 100644 --- a/R/data_modify.R +++ b/R/data_modify.R @@ -149,7 +149,17 @@ data_modify.data.frame <- function(data, ...) { if (!is.character(symbol)) { eval_symbol <- .dynEval(symbol, ifnotfound = NULL) if (is.character(eval_symbol)) { - symbol <- str2lang(paste0(names(dots)[i], " = ", eval_symbol)) + symbol <- try(str2lang(paste0(names(dots)[i], " = ", eval_symbol)), silent = TRUE) + # we may have the edge-case of having a function that returns a character + # vector, like "new_var = sample(letters[1:3])". In this case, "eval_symbol" + # is of type character, but no symbol, thus str2lang() above creates a + # wrong pattern. We then take "eval_symbol" as character input. + if (inherits(symbol, "try-error")) { + symbol <- str2lang(paste0( + names(dots)[i], + " = c(", paste0("\"", eval_symbol, "\"", collapse = ","), ")" + )) + } } } diff --git a/tests/testthat/test-data_modify.R b/tests/testthat/test-data_modify.R index b9f3d8fc8..661993ca5 100644 --- a/tests/testthat/test-data_modify.R +++ b/tests/testthat/test-data_modify.R @@ -482,3 +482,11 @@ test_that("data_modify works with grouped df when overwriting existing variables ) expect_equal(head(out$Sepal.Length2), 2 * c(0.53333, 0.4, 0.26667, 0.2, 0.46667, 0.73333), tolerance = 1e-3) }) + + +test_that("data_modify works with functions that return character vectors", { + data(iris) + set.seed(123) + out <- data_modify(iris, grp = sample(letters[1:3], nrow(iris), TRUE)) + expect_identical(head(out$grp), c("c", "c", "c", "b", "c", "b")) +})