diff --git a/NEWS.md b/NEWS.md index d5f85fe..ab65f90 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,3 +1,10 @@ +# poorman 0.2.7.9000 (devel) + +The following fixes were also implemented: + +* `relocate()` now works correctly when its arguments `.before` and `.after` + are passed through a function (#114, @etiennebacher). + # poorman 0.2.6 This update adds the following features: diff --git a/R/relocate.R b/R/relocate.R index ac3f731..9a26ab1 100644 --- a/R/relocate.R +++ b/R/relocate.R @@ -51,8 +51,26 @@ relocate.data.frame <- function(.data, ..., .before = NULL, .after = NULL) { data_names <- colnames(.data) col_pos <- select_positions(.data, ...) - if (!missing(.before)) .before <- colnames(.data)[eval_select_pos(.data, substitute(.before))] - if (!missing(.after)) .after <- colnames(.data)[eval_select_pos(.data, substitute(.after))] + if (!missing(.before)) { + x <- try(eval(.before), silent = TRUE) + if (inherits(x, "try-error")) { + .before <- colnames(.data)[eval_select_pos(.data, substitute(.before))] + } else if (is.null(x)) { + .after <- NULL + } else { + .before <- colnames(.data)[eval_select_pos(.data, .before)] + } + } + if (!missing(.after)) { + x <- try(eval(.after), silent = TRUE) + if (inherits(x, "try-error")) { + .after <- colnames(.data)[eval_select_pos(.data, substitute(.after))] + } else if (is.null(x)) { + .after <- NULL + } else { + .after <- colnames(.data)[eval_select_pos(.data, .after)] + } + } has_before <- !is.null(.before) has_after <- !is.null(.after) diff --git a/inst/tinytest/test_relocate.R b/inst/tinytest/test_relocate.R index 7c1778d..0dbaaf9 100644 --- a/inst/tinytest/test_relocate.R +++ b/inst/tinytest/test_relocate.R @@ -44,3 +44,23 @@ expect_error( mtcars %>% relocate(gear, .after = mpg, .before = cyl), info = "relocate() fails when .after and .before are both given" ) + +myFun <- function(location) { + relocate(mtcars, gear, .after = location) +} + +expect_equal( + myFun(1), + mtcars[, c("mpg", "gear", "cyl", "disp", "hp", "drat", "wt", "qsec", "vs", "am", "carb")], + info = "relocate() works when .after is passed through a function" +) + +myFun <- function(location) { + relocate(mtcars, gear, .before = location) +} + +expect_equal( + myFun(1), + mtcars[, c("gear", "mpg", "cyl", "disp", "hp", "drat", "wt", "qsec", "vs", "am", "carb")], + info = "relocate() works when .before is passed through a function" +)