For some objects an attribute identifies a special column, for example the geometry column in an sf
object. For conducting some calculations in dplyr
it would be good to easily identify these columns. I'm searching for a way to create a function that helps identifying this column. In the example below I can make a function that identifies this column but I still need to use the rlang
splice operator (!!!
).
require(sf)
require(dplyr)
n<-4
df = st_as_sf(data.frame(x = 1:n, y = 1:n, cat=gl(2,2)), coords = 1:2, crs = 3857) %>% group_by(cat)
# this is the example I start from however the geometry column is not guaranteed to have that name
df %>% mutate(d=st_distance(geometry, geometry[row_number()==1]))
#> Simple feature collection with 4 features and 2 fields
#> Geometry type: POINT
#> Dimension: XY
#> Bounding box: xmin: 1 ymin: 1 xmax: 4 ymax: 4
#> Projected CRS: WGS 84 / Pseudo-Mercator
#> # A tibble: 4 × 3
#> # Groups: cat [2]
#> cat geometry d[,1]
#> * <fct> <POINT [m]> [m]
#> 1 1 (1 1) 0
#> 2 1 (2 2) 1.41
#> 3 2 (3 3) 0
#> 4 2 (4 4) 1.41
# this works, however the code does not get easier to read
df %>% mutate(d=st_distance(!!!syms(attr(., "sf_column")), (!!!syms(attr(., "sf_column")))[row_number()==1]))
#> Simple feature collection with 4 features and 2 fields
#> ...
#> 4 2 (4 4) 1.41
# this works and is already better:
geometry_name<-function(x) syms(attr(x, 'sf_column'))
df %>% mutate(d=st_distance(!!!geometry_name(.), (!!!geometry_name(.))[row_number()==1]))
#> Simple feature collection with 4 features and 2 fields
#> ...
#> 4 2 (4 4) 1.41
Ideally I would like to find a function that makes the following code work as this would be easiest for users:
df %>% mutate(d=st_distance(geometry_name(), geometry_name()[row_number()==1]))