Skip to content

Instantly share code, notes, and snippets.

@rafapereirabr
Last active January 29, 2021 19:13
Show Gist options
  • Save rafapereirabr/217a7b46b37c1ff87f002380f434a3e4 to your computer and use it in GitHub Desktop.
Save rafapereirabr/217a7b46b37c1ff87f002380f434a3e4 to your computer and use it in GitHub Desktop.
Assign NA value to neighbor polygon with largest pop
```
library(sf)
library(geobr)
# sample spatial data
df <- read_state()
# create random pop and cases
df$pop <- sample(1:27, 27, replace = T)
df$cases <- sample(1:10, 27, replace = T)
# impute a couple NAs
df$pop[7] <- NA
df$pop[10] <- NA
# list polygons with NA pop
na_ids <- rownames(df)[which(is.na(df$pop))] %>% as.numeric()
for (i in na_ids){
# find neighbor polygons
nei_index <- st_intersects( df[i,] , df)
nei_index <- unlist(nei_index, use.names=FALSE)
nei_poly <- df[nei_index,]
# find neighbor polygon with largest pop
target_poly <- rownames(nei_poly)[which(nei_poly$pop == max(nei_poly$pop, na.rm=T) )][1] %>% as.numeric()
# get cases from problematic polygon and assign them to target_poly
df$cases[target_poly] <- df$cases[target_poly] + df$cases[i]
# update cases in problematic polygon to zero
df$cases[i] <- 0
df$pop[i] <- 0
}
summary(df$pop)
summary(df$cases)
```
library(sf)
library(geobr)
# sample spatial data
states_sf <- read_state()
# create panel with 2 weeks
df <- rbind(states_sf, states_sf, states_sf)
df$week <- c(rep(1, 27), rep(2, 27), rep(3, 27))
# create random pop and cases
set.seed(0)
df$pop <- sample(20:100, 27, replace = T) %>% rep(.,3)
df$cases <- sample(0:19, nrow(df), replace = T)
# impute a couple NAs
df$pop[1] <- NA
df$pop[28] <- NA
# list polygons with NA pop
# na_ids <- rownames(df)[which(is.na(df$pop))] %>% as.numeric()
na_ids <- df$code_state[which(is.na(df$pop))] %>% as.numeric() %>% unique()
# list weeks when there is at list one NA pop
na_weeks <- df$week[which(is.na(df$pop))] %>% as.numeric() %>% unique()
for (i in na_ids){
# find neighbor polygons
nei_index <- st_intersects( subset(df, code_state==i)[1,] , df[1:length(unique(df$code_state)),] )
nei_index <- unlist(nei_index, use.names=FALSE)
nei_poly <- df[nei_index,]
# find neighbor polygon with largest pop
target_poly <- rownames(nei_poly)[which(nei_poly$pop == max(nei_poly$pop, na.rm=T) )][1] %>% as.numeric()
# Assign cases in each week
for (j in na_weeks){
# get cases from problematic polygon and assign them to target_poly
df$cases[which(df$week==j)][target_poly] <- df$cases[which(df$week==j)][target_poly] + df$cases[which(df$week==j & df$code_state==i)]
# update cases in problematic polygon to zero
df$cases[which(df$week==j & df$code_state==i)] <- 0
}
}
summary(df$pop)
summary(df$cases)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment