Skip to content

Commit

Permalink
fix: relocate() works when .before and .after called in a function
Browse files Browse the repository at this point in the history
  • Loading branch information
etiennebacher committed Aug 27, 2022
1 parent bbb9aed commit e7ed1c6
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 2 deletions.
7 changes: 7 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -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:
Expand Down
18 changes: 16 additions & 2 deletions R/relocate.R
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,22 @@ 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_expr(.before), silent = TRUE)
if (inherits(x, "try-error")) {
.before <- colnames(.data)[eval_select_pos(.data, substitute(.before))]
} else {
.before <- colnames(.data)[eval_select_pos(.data, .before)]
}
}
if (!missing(.after)) {
x <- try(eval_expr(.after), silent = TRUE)
if (inherits(x, "try-error")) {
.after <- colnames(.data)[eval_select_pos(.data, substitute(.after))]
} else {
.after <- colnames(.data)[eval_select_pos(.data, .after)]
}
}

has_before <- !is.null(.before)
has_after <- !is.null(.after)
Expand Down
20 changes: 20 additions & 0 deletions inst/tinytest/test_relocate.R
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)

0 comments on commit e7ed1c6

Please sign in to comment.