diff --git a/R/data_modify.R b/R/data_modify.R index f1d6fa5c6..7dbcc5319 100644 --- a/R/data_modify.R +++ b/R/data_modify.R @@ -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 diff --git a/tests/testthat/test-data_modify.R b/tests/testthat/test-data_modify.R index dac902d66..66453b6c0 100644 --- a/tests/testthat/test-data_modify.R +++ b/tests/testthat/test-data_modify.R @@ -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)) })