Skip to content

Instantly share code, notes, and snippets.

@clanfear
Created August 15, 2019 18:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save clanfear/e160ba2ddf5e90c7bc70dbd2cfb0dd94 to your computer and use it in GitHub Desktop.
Save clanfear/e160ba2ddf5e90c7bc70dbd2cfb0dd94 to your computer and use it in GitHub Desktop.
Using sf and tidyverse to get weighted mean of neighbors for all columns
library(tidyverse)
library(sf)
st_queen <- function(a, b = a){
st_relate(a, b, pattern = "F***T****")
}
new_data <- original_data %>%
mutate(neighbors = st_queen(.)) %>%
st_drop_geometry() %>%
select(unit_id, neighbors) %>%
tidyr::unnest(neighbors) %>%
mutate(neighbor_id = original_data$unit_id[neighbors]) %>%
left_join(original_data, by = c("neighbor_id"="unit_id")) %>%
select(-neighbors, -neighbor_id) %>%
group_by(unit_id) %>%
summarize_all(~mean(.)) %>%
left_join(original_data, by = "unit_id")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment