Skip to content

Commit

Permalink
Fix issue where the sf package "sf_column" may not be the last column…
Browse files Browse the repository at this point in the history
… in an sf object
  • Loading branch information
billdenney committed Sep 12, 2024
1 parent cd47202 commit b052e2d
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 5 deletions.
2 changes: 2 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ These are all minor breaking changes resulting from enhancements and are not exp

* `get_one_to_one()` no longer errors with near-equal values that become identical factor levels (fix #543, thanks to @olivroy for reporting)

* `clean_names()` for sf objects now works in cases when the sf_column is not the last column name (fix #578, thanks to @ar-puuk for reporting and @billdenney for fixing)

## Refactoring

* Remove dplyr verbs superseded in dplyr 1.0.0 (#547, @olivroy)
Expand Down
10 changes: 5 additions & 5 deletions R/clean_names.R
Original file line number Diff line number Diff line change
Expand Up @@ -97,14 +97,14 @@ clean_names.sf <- function(dat, ...) {
} # nocov end
# get old names
sf_names <- names(dat)
# identify ending column index to clean
n_cols <- length(dat) - 1
# Clean the names except for the "sf_column" which is used internally by sf
cols_to_rename <- which(!(sf_names %in% attr(dat, "sf_column")))
# clean all but last column
sf_cleaned <- make_clean_names(sf_names[1:n_cols], ...)
sf_cleaned <- make_clean_names(sf_names[cols_to_rename], ...)
# rename original df
names(dat)[1:n_cols] <- sf_cleaned
names(dat)[cols_to_rename] <- sf_cleaned

return(dat)
dat
}

#' @rdname clean_names
Expand Down
9 changes: 9 additions & 0 deletions tests/testthat/test-clean-names.R
Original file line number Diff line number Diff line change
Expand Up @@ -461,6 +461,15 @@ test_that("Names are cleaned appropriately without attaching sf", {

expect_equal(names(clean)[4], "cnty_id")
expect_s3_class(clean, "sf")

# Issue #578, sf_column attribute needs to be untouched, it may not be the
# last column name
issue_578_sf <- readRDS("testdata/issue-578-sf.rds")
issue_578_sf_clean <- clean_names(issue_578_sf)
expect_error(
print(issue_578_sf_clean),
NA
)
})

test_that("Names are cleaned appropriately", {
Expand Down
Binary file added tests/testthat/testdata/issue-578-sf.rds
Binary file not shown.

0 comments on commit b052e2d

Please sign in to comment.