Skip to content

Commit d86920e

Browse files
committed
Fix rename_with() and add tests (#2215)
1 parent 3540489 commit d86920e

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

R/tidyverse.R

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -239,10 +239,19 @@ rename_with.sf = function(.data, .fn, .cols, ...) {
239239
if (!requireNamespace("rlang", quietly = TRUE))
240240
stop("rlang required: install that first") # nocov
241241
.fn = rlang::as_function(.fn)
242+
243+
sf_column = attr(.data, "sf_column")
244+
sf_column_loc = match(sf_column, names(.data))
245+
246+
if (length(sf_column_loc) != 1 || is.na(sf_column_loc))
247+
stop("internal error: can't find sf column") # nocov
248+
242249
agr = st_agr(.data)
250+
243251
ret = NextMethod()
244252
names(agr) = .fn(names(agr))
245253
st_agr(ret) = agr
254+
st_geometry(ret) = names(ret)[sf_column_loc]
246255
ret
247256
}
248257

tests/testthat/test_tidy.R

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -255,6 +255,17 @@ test_that("can rename geometry column with `rename()` (#1431)", {
255255
)
256256
})
257257

258+
test_that("`rename_with()` correctly changes the sf_column attribute (#2215)", {
259+
skip_if_not_installed("dplyr")
260+
261+
sf_column = attr(nc, "sf_column")
262+
fn = function(x) paste0(x, "_renamed")
263+
264+
expect_equal(nc %>% rename_with(fn) %>% attr("sf_column"), fn(sf_column))
265+
expect_equal(nc %>% rename_with(fn, "NAME") %>% attr("sf_column"), sf_column)
266+
expect_equal(nc %>% rename_with(fn, "geometry") %>% attr("sf_column"), fn(sf_column))
267+
})
268+
258269
test_that("`select()` and `transmute()` observe back-stickiness of geometry column (#1425)", {
259270
skip_if_not_installed("dplyr")
260271
sf = read_sf(system.file("shape/nc.shp", package = "sf"))

0 commit comments

Comments
 (0)