Skip to content

Commit

Permalink
address comment, fix tests
Browse files Browse the repository at this point in the history
  • Loading branch information
strengejacke committed Feb 6, 2024
1 parent 494356e commit dd6fbc4
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 23 deletions.
24 changes: 9 additions & 15 deletions R/data_modify.R
Original file line number Diff line number Diff line change
Expand Up @@ -352,22 +352,16 @@ data_modify.grouped_df <- function(data, ..., .if = NULL, .at = NULL, .modify =
.misspelled_string(column_names, not_found, "Possibly misspelled or not yet defined?")
)
}
# modify variables
found <- .at[.at %in% column_names]
if (length(found)) {
for (i in found) {
result <- tryCatch(.modify(data[[i]]), warning = function(e) e, error = function(e) e)
if (inherits(result, c("error", "warning"))) {
insight::format_error(
paste0("Error in modifying variable \"", i, "\": ", result$message),
"Please check if you correctly specified the `.modify` function."
)
} else {
data[[i]] <- result
}
for (i in .at) {
result <- tryCatch(.modify(data[[i]]), warning = function(e) e, error = function(e) e)
if (inherits(result, c("error", "warning"))) {
insight::format_error(
paste0("Error in modifying variable \"", i, "\": ", result$message),
"Please check if you correctly specified the `.modify` function."
)
} else {
data[[i]] <- result
}
} else {
insight::format_error("No variables found in the dataset that match the `.if` or `.at` argument.")
}

data
Expand Down
15 changes: 7 additions & 8 deletions tests/testthat/test-data_modify.R
Original file line number Diff line number Diff line change
Expand Up @@ -513,24 +513,23 @@ test_that("data_modify .if/.at arguments", {
data_modify(d, .at = "Species", .modify = "a"),
regex = "`.modify` must"
)
expect_message(
expect_error(
data_modify(d, .at = c("Species", "Test"), .modify = as.numeric),
regex = "Variable \"Test\""
)
expect_message(
expect_error(
data_modify(d, .at = c("Species", "Hi", "Test"), .modify = as.numeric),
regex = "Variables \"Hi\" and \"Test\""
)
expect_message(
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(
expect_error(
data_modify(d, .at = "Species", .modify = function(x) 2 * x),
regex = "Warning when modifying variable"
regex = "Error in modifying variable"
)
# newly created variables are not modified by if/at
out <- data_modify(d, new_length = Petal.Length * 2, .if = is.numeric, .modify = as.factor)
expect_identical(out$new_length, c(2.8, 2.8, 2.6, 3, 2.8))
})

0 comments on commit dd6fbc4

Please sign in to comment.