Skip to content

Commit

Permalink
throw informative messages on invalid .modify
Browse files Browse the repository at this point in the history
  • Loading branch information
strengejacke committed Feb 6, 2024
1 parent 63de575 commit 3007fa3
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
20 changes: 19 additions & 1 deletion R/data_modify.R
Original file line number Diff line number Diff line change
Expand Up @@ -341,7 +341,25 @@ data_modify.grouped_df <- function(data, ..., .if = NULL, .at = NULL, .modify =
found <- .at[.at %in% column_names]
if (length(found)) {
for (i in found) {
data[[i]] <- .modify(data[[i]])
result <- tryCatch(
.modify(data[[i]]),
warning = function(e) e,
error = function(e) e
)
if (inherits(result, "error")) {
insight::format_error(
paste0("Error in modifying variable \"", i, "\": ", result$message),
"Please check if you correctly specified the `.modify` function."
)
} else if (inherits(result, "warning")) {
insight::format_warning(
paste0("Warning when modifying variable \"", i, "\": ", result$message),
"Results may be incorrect or unexpected."
)
data[[i]] <- result
} else {
data[[i]] <- result
}
}
} else {
insight::format_alert("No variables found in the dataset that match the `.if` or `.at` argument.")
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 @@ -525,4 +525,12 @@ test_that("data_modify .if/.at arguments", {
data_modify(d, .at = c("Hi", "Test"), .modify = as.numeric),
regex = "No variables found in the dataset"
)
expect_error(
data_modify(d, .at = "Species", .modify = function(x) 2 / y + x),
regex = "Error in modifying variable"
)
expect_warning(
data_modify(d, .at = "Species", .modify = function(x) 2 * x),
regex = "Warning when modifying variable"
)
})

0 comments on commit 3007fa3

Please sign in to comment.