library(eurostat)
library(tidyverse)
library(tmap)
library(sf)
library(DT)
# Load GDP
gdp <- get_eurostat("nama_10r_2gdp") 
emp <- get_eurostat("nama_10r_3empers") 


NUTS2016 <- readxl::read_xlsx("NUTS2016.xlsx") %>% 
  filter(NUTS!="3") %>% 
  mutate_if(is.character,as.factor) %>% 
  mutate(NUTS=as.factor(NUTS)) %>% 
  filter(!Country %in% c("UK","IS","NO","CH","LI","ME","MK","RS","TR","AL"))
gdpw <- gdp %>% 
  filter(time=="2019-01-01" &
         unit=="MIO_PPS_EU27_2020" ) %>% 
  rename (gdp= values) %>% 
  select(-time, -unit)

empw <- emp %>% 
  filter(time=="2019-01-01" &
         nace_r2=="TOTAL"&
          wstatus=="EMP") %>% 
  rename (emp= values) %>% 
  select(-time, -unit, -nace_r2, -wstatus)

df<- left_join(gdpw, empw)

df<- left_join(df, NUTS2016) %>% 
 mutate(gdp_emp=gdp*1000/emp,
        gdp_emp_eu=gdp_emp*100/gdp_emp[geo=="EU27_2020"]) %>% 
  mutate(gdp_emp=round(gdp_emp, digits = -2),
         gdp_emp_eu=round(gdp_emp_eu, digits= 0)) %>% 
  filter(label!="Extra-regio")

GDP per person employed in PPS in 2019, EU27=100

datatable(df, filter = "top", class = "stripe hover", extensions = "Buttons",
             options = list(  lengthMenu = list(c(20,50,200, -1), c("20","50","200", "All")),
                              pageLength = 50, autoWidth = TRUE,  dom = "Blfrtip", buttons = c("excel")),
             rownames= FALSE
)  
load(file="nuts_map.Rdata")

sf<- left_join (nuts, df) 

sf<- sf %>% 
  filter(!CNTR_CODE %in% c("UK","IS","NO","CH","LI"))

tmap_mode("view")
sf %>% filter(LEVL_CODE=="2" )  %>% 
tm_shape() +
tm_fill("gdp_emp_eu", popup.vars = c("gdp_emp","gdp_emp_eu","NUTS_ID","NUTS_NAME"), palette="RdBu", style="fixed",  breaks = c(36,65,80,100,120,256), title="GDP per person empployed in PPS as % EU average, 2019")+
  tm_borders()