Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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