diff --git a/R/tidyverse.R b/R/tidyverse.R index 96419f9a7..454959fb6 100644 --- a/R/tidyverse.R +++ b/R/tidyverse.R @@ -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 } diff --git a/tests/testthat/test_tidy.R b/tests/testthat/test_tidy.R index 492e5a0ec..151ecb410 100644 --- a/tests/testthat/test_tidy.R +++ b/tests/testthat/test_tidy.R @@ -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"))