library(geofi)
library(dplyr)
library(tidyr)
library(stringr)
library(ggplot2)
library(sf)

Käsitellään data

rivit <- 
"Osasto X | 00100-00150
Osasto Y | 00200-00250
Osasto Z | 40100-40500" 
dat0 <- read.table(textConnection(rivit), 
                   header = FALSE, 
                   sep = "|", 
                   stringsAsFactors = FALSE) %>% 
  separate(col = V2, into = c("zip_min","zip_max"), sep = "-") %>% 
  mutate_at(.vars = vars(contains("zip")), as.integer) %>% 
  rename(osasto = V1) %>% 
  mutate(osasto = str_trim(osasto))
dat0
##     osasto zip_min zip_max
## 1 Osasto X     100     150
## 2 Osasto Y     200     250
## 3 Osasto Z   40100   40500
ziplist <- list()
for (i in unique(dat0$osasto)){
  ziplist[[i]] <- tibble(zips = seq.int(from = dat0[dat0$osasto == i,]$zip_min, 
                                        to = dat0[dat0$osasto == i,]$zip_max, 
                                        by = 1),
                         osasto = i)
}
df_zips <- do.call(bind_rows, ziplist)
head(df_zips)
## # A tibble: 6 x 2
##    zips osasto  
##   <dbl> <chr>   
## 1   100 Osasto X
## 2   101 Osasto X
## 3   102 Osasto X
## 4   103 Osasto X
## 5   104 Osasto X
## 6   105 Osasto X

Haetaan postinumeroalueet ja yhdistetään

zipcodes <- get_zipcodes()
map <- right_join(zipcodes %>% 
                    mutate(posti_alue = as.integer(as.character((posti_alue)))), 
                  df_zips, by = c("posti_alue" = "zips")) %>% 
  filter(!is.na(osasto)) 

Staattinen kartta

# Haetaan kuntarajat myös ja aggregoidaan siitä koko maan raja
get_municipalities() %>% 
  st_union() -> fin 
  

ggplot(map) + 
  # koko Suomen rajat
  geom_sf(data = fin, fill = NA, color = "white") +
  geom_sf(aes(fill = osasto)) 

Vuorovaikutteinen kartta

# Interaktiivinen kartta
library(leaflet)
map <- sf::st_transform(x = map, crs = "+proj=longlat +datum=WGS84")

pal <- colorFactor(domain = map$osasto, palette = "Set1")

labels <- sprintf(
  "%s (%s)<br/>%s",
  map$nimi,str_pad(map$posti_alue, width = 5, pad = 0), map$osasto
) %>% lapply(htmltools::HTML)

leaflet(map) %>% 
  addProviderTiles(provider = providers$CartoDB.Positron) %>% 
  addPolygons(fillColor = ~pal(osasto), 
              fillOpacity = .7,
              color = alpha("white",1/3),
              label = labels) %>% 
  addLegend(data = map, 
            pal = pal, 
            values = ~osasto, 
            opacity = 0.7,
            position = "bottomright")