Skip to content

Commit

Permalink
data_modify works with functions that return character vectors
Browse files Browse the repository at this point in the history
  • Loading branch information
strengejacke committed Jun 14, 2023
1 parent e78ae5c commit f477241
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 2 deletions.
2 changes: 1 addition & 1 deletion DESCRIPTION
Original file line number Diff line number Diff line change
@@ -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", , "[email protected]", role = "aut",
comment = c(ORCID = "0000-0003-1995-6531", Twitter = "@patilindrajeets")),
Expand Down
12 changes: 11 additions & 1 deletion R/data_modify.R
Original file line number Diff line number Diff line change
Expand Up @@ -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 = ","), ")"
))
}
}
}

Expand Down
8 changes: 8 additions & 0 deletions tests/testthat/test-data_modify.R
Original file line number Diff line number Diff line change
Expand Up @@ -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"))
})

0 comments on commit f477241

Please sign in to comment.