I'm quite new to spatial analyses in R using the
sf package, so I could use some help.
I have a data frame with point coordinates. For each row, observation, in the data frame, I want to find how many other observations are within x meters. My attempts so far have led me to use
st_is_within_distance as the type of join, and join the data frame with itself. The following code gives an example of this approach for a data frame in
spDataand x set to 100 meters:
library(tidyverse) #> Warning: package 'tibble' was built under R version 4.0.4 #> Warning: package 'tidyr' was built under R version 4.0.4 #> Warning: package 'dplyr' was built under R version 4.0.4 #> Warning: package 'forcats' was built under R version 4.0.4 library(sf) #> Warning: package 'sf' was built under R version 4.0.4 #> Linking to GEOS 3.9.0, GDAL 3.2.1, PROJ 7.2.1 library(spData) #> Warning: package 'spData' was built under R version 4.0.5 #> To access larger datasets in this package, install the spDataLarge #> package with: `install.packages('spDataLarge', #> repos='https://nowosad.github.io/drat/', type='source')` cycle_hire_P <- st_transform(cycle_hire, 27700) cycle_hire_neigbours <- st_join(cycle_hire_P, cycle_hire_P %>% select(geometry), join = st_is_within_distance, dist = 100) %>% st_drop_geometry() %>% group_by(id, name, area) %>% summarise(no_neigbours = sum(n())) #> `summarise()` has grouped output by 'id', 'name'. You can override using the `.groups` argument. head(cycle_hire_neigbours) #> # A tibble: 6 x 4 #> # Groups: id, name  #> id name area no_neigbours #> <int> <fct> <fct> <int> #> 1 1 River Street Clerkenwell 1 #> 2 2 Phillimore Gardens Kensington 1 #> 3 3 Christopher Street Liverpool Street 2 #> 4 4 St. Chad's Street King's Cross 1 #> 5 5 Sedding Street Sloane Square 1 #> 6 6 Broadcasting House Marylebone 1
Created on 2021-05-23 by the reprex package (v1.0.0)
As far as I know, this seems to work. But I have to make this type of calculation for a very, very big data frame, so I'm wondering if this is the best approach, or if I should try some other way. As mentioned, the
sf package is really new to me, so I'm not familiar with how to best use it.
Any help would be greatly appreciated!