## ----setup, include = FALSE---------------------------------------------------
knitr::opts_chunk$set(collapse = T, fig.align="center", dpi = 150, out.width = "100%", fig.width = 8, fig.height = 4)
library(httr)
library(roxygen2)

## ----census, echo = T, eval = T, message = F----------------------------------
library(RCzechia)
library(ggplot2)
library(readxl)
library(dplyr)
library(httr)
library(sf)

GET("https://raw.githubusercontent.com/jlacko/RCzechia/master/data-raw/zvcr034.xls", 
    write_disk(tf <- tempfile(fileext = ".xls")))

src <- read_excel(tf, range = "Data!B5:C97") # read in with original column names

colnames(src) <- c("NAZ_LAU1", "obyvatel") # meaningful names instead of the original ones

src <- src %>%
  mutate(obyvatel = as.double(obyvatel)) %>% 
    # convert from text to number
  mutate(NAZ_LAU1 = ifelse(NAZ_LAU1 == "Hlavní město Praha", "Praha", NAZ_LAU1)) 
    # rename Prague (from The Capital to a regular city)
  
okresni_data <- RCzechia::okresy("low") %>% # data shapefile
  inner_join(src, by = "NAZ_LAU1") 
    # key for data connection - note the use of inner (i.e. filtering) join

ggplot(data = okresni_data) +
  geom_sf(aes(fill = obyvatel), colour = NA) +
  geom_sf(data = republika(), color = "gray30", fill = NA) +
  scale_fill_viridis_c(trans = "log", labels = scales::comma) +
  labs(title = "Czech population",
       fill = "population\n(log scale)") +
  theme_bw() +
  theme(legend.text.align = 1,
        legend.title.align = 0.5)





## ----geocode, echo = T, eval = T, message = F, warning = F,fig.width = 8, fig.height = 5----
library(RCzechia)
library(ggplot2)
library(sf)

borders <- RCzechia::republika("low")

rivers <- subset(RCzechia::reky(), Major == T)

mista <- data.frame(misto =  c("Kramářova vila", 
                               "Arcibiskupské zahrady v Kromeříži", 
                               "Hrad Bečov nad Teplou"),
                    adresa = c("Gogolova 1, Praha 1",
                               "Sněmovní náměstí 1, Kroměříž",
                               "nám. 5. května 1, Bečov nad Teplou"))

# from a string vector to sf spatial points object
POI <- RCzechia::geocode(mista$adresa) 

ggplot() +
  geom_sf(data = POI, color = "red", shape = 4, size = 2) +
  geom_sf(data = rivers, color = "steelblue", alpha = 0.5) +
  geom_sf(data = borders, color = "grey30", fill = NA) +
  labs(title = "Very Special Places") +
  theme_bw()


## ----distance, echo = T, eval = T, message = F--------------------------------
library(dplyr)
library(RCzechia)
library(sf)
library(units)

obce <- RCzechia::obce_polygony()

praha <- subset(obce, NAZ_OBEC == "Praha")

brno <- subset(obce, NAZ_OBEC == "Brno")

vzdalenost <- sf::st_distance(praha, brno) %>%
  units::set_units("kilometers") # easier to interpret than meters, miles or decimal degrees..

print(vzdalenost)


## ----brno-center, echo = T, eval = T, message = F, fig.width = 6, fig.height = 6----
library(dplyr)
library(RCzechia)
library(ggplot2)
library(sf)

brno <- subset(RCzechia::obce_polygony(), NAZ_OBEC == "Brno")

pupek_brna <- brno %>%
  st_transform(5514) %>% # planar CRS (eastings & northings)
  st_set_agr('constant') %>%  # not strictly necessary, but avoids error message
  sf::st_centroid(brno) # calculate central point of a polygon

# the revgeo() function takes a sf points data frame and returns it back
# with address data in "revgeocoded"" column
adresa_pupku <- RCzechia::revgeo(pupek_brna)$revgeocoded

print(adresa_pupku)

ggplot() +
  geom_sf(data = pupek_brna, col = "red", shape = 4, size = 2) +
  geom_sf(data = brno, color = "grey30", fill = NA) +
  labs(title = "Geographical Center of Brno") +
  theme_bw()




## ----interactive, echo = T, eval = F------------------------------------------
#  library(dplyr)
#  library(RCzechia)
#  library(leaflet)
#  library(sf)
#  
#  src <- read.csv(url("https://raw.githubusercontent.com/jlacko/RCzechia/master/data-raw/unempl.csv"), stringsAsFactors = F)
#  # open data on unemployment from Czech Statistical Office - https://www.czso.cz/csu/czso/otevrena_data
#  # lightly edited for size (rows filtered)
#  
#  
#  src <- src %>%
#    mutate(KOD_OBEC = as.character(uzemi_kod))  # keys in RCzechia are of type character
#  
#  podklad <- RCzechia::obce_polygony() %>% # obce_polygony = municipalities in RCzechia package
#    inner_join(src, by = "KOD_OBEC") %>% # linking by key
#    filter(KOD_CZNUTS3 == "CZ071") # Olomoucký kraj
#  
#  pal <- colorNumeric(palette = "viridis",  domain = podklad$hodnota)
#  
#  leaflet() %>%
#    addProviderTiles("Stamen.Toner") %>%
#    addPolygons(data = podklad,
#                fillColor = ~pal(hodnota),
#                fillOpacity = 0.75,
#                color = NA)
#  

## ----union,  echo = T, eval = T, message = F----------------------------------
library(RCzechia)
library(ggplot2)
library(dplyr)
library(sf)


poly <- RCzechia::okresy("low") %>% # Czech LAU1 regions as sf data frame
  mutate(oddeven = ifelse(nchar(NAZ_LAU1) %% 2 == 1, "odd", "even" )) %>% # odd or even?
  RCzechia::union_sf("oddeven") # ... et facta est lux

# Structure of the "poly" object:
head(poly)

ggplot(data = poly, aes(fill = oddeven)) +
  geom_sf() +
  scale_fill_viridis_d() +
  labs(title = "Number of characters in names of Czech districts",
       fill = "Odd or even?") +
  theme_bw()


## ----ctverce, echo = T, eval = T, message = F, warning = F,fig.width = 8, fig.height = 5----
library(RCzechia)
library(ggplot2)
library(dplyr)
library(sf)

obec <- "Humpolec" # a Czech location

# geolocate centroid of a place
place <- RCzechia::geocode(obec) %>% 
  filter(typ == "Obec") 

# ID of the KFME square containg place geocoded
ctverec_id <- sf::st_intersection(RCzechia::KFME_grid(), place)$ctverec

print(paste0("Location found in grid cell number ", ctverec_id, "."))

# a single KFME square to be highlighted
highlighted_cell <- KFME_grid() %>% 
  filter(ctverec == ctverec_id) 

# a summary plot
ggplot() +
  geom_sf(data = RCzechia::republika(), size = .85) + # Czech borders
  geom_sf(data = highlighted_cell, # a specific KFME cell ...
          fill = "limegreen", alpha = .5) +  # ... highlighted in lime green
  geom_sf(data = KFME_grid(), size = .33, # all KFME grid cells, thin
          color = "gray80", fill = NA) + # in gray and without fill
  geom_sf(data = place,  color = "red", pch = 4) +  # X marks the spot!
  ggtitle(paste("Location", obec, "in grid cell number", ctverec_id)) +
  theme_bw()


## ----relief, echo = T, eval = T, message = F, warning = F,fig.width = 8, fig.height = 5----
library(RCzechia)
library(ggplot2)
library(dplyr)
library(raster)

# ggplot does not play nice with {raster} package; a data frame is required
relief <- vyskopis("rayshaded") %>% 
  as("SpatialPixelsDataFrame") %>% 
  as_tibble()

ggplot() +
  geom_raster(data = relief, aes(x = x, y  = y, alpha = -raytraced), # relief
              fill = "gray30",  show.legend = F) + # no legend is necessary
  geom_sf(data = subset(RCzechia::reky(), Major == T), # major rivers
          color = "steelblue", alpha = .7) +
  labs(title = "Czech Rivers & Their Basins") +
  theme_bw() +
  theme(axis.title = element_blank())


