Skip to content

Commit

Permalink
Fix rename_with() and add tests (#2215)
Browse files Browse the repository at this point in the history
  • Loading branch information
UchidaMizuki committed Aug 20, 2023
1 parent 3540489 commit d86920e
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
9 changes: 9 additions & 0 deletions R/tidyverse.R
Original file line number Diff line number Diff line change
Expand Up @@ -239,10 +239,19 @@ rename_with.sf = function(.data, .fn, .cols, ...) {
if (!requireNamespace("rlang", quietly = TRUE))
stop("rlang required: install that first") # nocov
.fn = rlang::as_function(.fn)

sf_column = attr(.data, "sf_column")
sf_column_loc = match(sf_column, names(.data))

if (length(sf_column_loc) != 1 || is.na(sf_column_loc))
stop("internal error: can't find sf column") # nocov

agr = st_agr(.data)

ret = NextMethod()
names(agr) = .fn(names(agr))
st_agr(ret) = agr
st_geometry(ret) = names(ret)[sf_column_loc]
ret
}

Expand Down
11 changes: 11 additions & 0 deletions tests/testthat/test_tidy.R
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,17 @@ test_that("can rename geometry column with `rename()` (#1431)", {
)
})

test_that("`rename_with()` correctly changes the sf_column attribute (#2215)", {
skip_if_not_installed("dplyr")

sf_column = attr(nc, "sf_column")
fn = function(x) paste0(x, "_renamed")

expect_equal(nc %>% rename_with(fn) %>% attr("sf_column"), fn(sf_column))
expect_equal(nc %>% rename_with(fn, "NAME") %>% attr("sf_column"), sf_column)
expect_equal(nc %>% rename_with(fn, "geometry") %>% attr("sf_column"), fn(sf_column))
})

test_that("`select()` and `transmute()` observe back-stickiness of geometry column (#1425)", {
skip_if_not_installed("dplyr")
sf = read_sf(system.file("shape/nc.shp", package = "sf"))
Expand Down

0 comments on commit d86920e

Please sign in to comment.