diff --git a/NEWS.md b/NEWS.md index c4356e6..73de1b0 100644 --- a/NEWS.md +++ b/NEWS.md @@ -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) diff --git a/R/clean_names.R b/R/clean_names.R index b8fe3b5..ee8efe6 100644 --- a/R/clean_names.R +++ b/R/clean_names.R @@ -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 diff --git a/tests/testthat/test-clean-names.R b/tests/testthat/test-clean-names.R index 96e8809..45ea6e3 100644 --- a/tests/testthat/test-clean-names.R +++ b/tests/testthat/test-clean-names.R @@ -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", { diff --git a/tests/testthat/testdata/issue-578-sf.rds b/tests/testthat/testdata/issue-578-sf.rds new file mode 100644 index 0000000..5c20894 Binary files /dev/null and b/tests/testthat/testdata/issue-578-sf.rds differ