Created
          August 15, 2019 18:44 
        
      - 
      
 - 
        
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
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | 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