从版本1.0-13开始,sf
有一个新方法:rename_with.sf
:
sf:::rename_with.sf
#> function (.data, .fn, .cols, ...)
#> {
#> if (!requireNamespace("rlang", quietly = TRUE))
#> stop("rlang required: install that first")
#> .fn = rlang::as_function(.fn)
#> agr = st_agr(.data)
#> ret = NextMethod()
#> names(agr) = .fn(names(agr))
#> st_agr(ret) = agr
#> ret
#> }
#> <bytecode: 0x00000235ee991c48>
#> <environment: namespace:sf>
这意味着在本例中,...
不会像rename_with.data.frame
那样传递给函数:
dplyr:::rename_with.data.frame
#> function (.data, .fn, .cols = everything(), ...)
#> {
#> .fn <- as_function(.fn)
#> cols <- tidyselect::eval_select(enquo(.cols), .data, allow_rename = FALSE)
#> names <- names(.data)
#> sel <- vec_slice(names, cols)
#> new <- .fn(sel, ...)
#> if (!is_character(new)) {
#> cli::cli_abort("{.arg .fn} must return a character vector, not {.obj_type_friendly {new}}.")
#> }
#> if (length(new) != length(sel)) {
#> cli::cli_abort("{.arg .fn} must return a vector of length {length(sel)}, not {length(new)}.")
#> }
#> names <- vec_assign(names, cols, new)
#> names <- vec_as_names(names, repair = "check_unique")
#> set_names(.data, names)
#> }
#> <bytecode: 0x00000235ee381aa0>
#> <environment: namespace:dplyr>
对于一种可行的方法,您可以try 使用purrr
函数显式传递参数:
library(tidyverse)
library(sf)
download.file("https://www2.census.gov/geo/tiger/TIGER_RD18/LAYER/CD/tl_rd22_01_cd118.zip", "tl_rd22_01_cd118.zip")
unzip("tl_rd22_01_cd118.zip")
st_read('tl_rd22_01_cd118.shp', quiet = TRUE) |>
rename_with(~ str_remove(.x, pattern = '\\d{2}$'))
#> Simple feature collection with 7 features and 12 fields
#> Geometry type: MULTIPOLYGON
#> Dimension: XY
#> Bounding box: xmin: -88.47323 ymin: 30.14442 xmax: -84.88825 ymax: 35.00803
#> Geodetic CRS: NAD83
#> STATEFP GEOID CD118FP NAMELSAD LSAD CDSESSN MTFCC FUNCSTAT
#> 1 01 0101 01 Congressional District 1 C2 118 G5200 N
#> 2 01 0102 02 Congressional District 2 C2 118 G5200 N
#> 3 01 0103 03 Congressional District 3 C2 118 G5200 N
#> 4 01 0104 04 Congressional District 4 C2 118 G5200 N
#> 5 01 0105 05 Congressional District 5 C2 118 G5200 N
#> 6 01 0106 06 Congressional District 6 C2 118 G5200 N
#> 7 01 0107 07 Congressional District 7 C2 118 G5200 N
...
或者在函数调用中显式使用dplyr:::rename_with.data.frame
方法:
st_read('tl_rd22_01_cd118.shp', quiet = TRUE) |>
dplyr:::rename_with.data.frame(., .fn = str_remove, pattern = '\\d{2}$')
编辑建议的修复
我会建议GitHub的一个潜在修复,因为我认为最容易的调整是将this line从:
names(agr) = .fn(names(agr))
致:
names(agr) = .fn(names(agr), ...)