<p><div><div><div><div data-width="100" data-show-faces="false" data-send="true" data-layout="button_count" data-height="21" data-href="https://www.r-bloggers.com/r-gis-and-fuzzyjoin-to-reconstruct-demographic-data-for-nuts-regions-of-denmark/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://ikashnitsky.github.io/2017/denmark-nuts-reconstruction/"> Ilya Kashnitsky</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<h2>NUTS</h2>
<p>NUTS stands for the <a target="_blank" rel="nofollow" href="http://ec.europa.eu/eurostat/web/nuts/overview"><em>Nomenclature of Territorial Units For Statistics</em></a>. The history of NUTS dates back to the beginning of 1970s, when European countries developed unified standards for systems of administrative geography. It was not until the beginning of this century when such a system finally became widely used. There are three main hierarchical levels of NUTS, and the most commonly used for regional analysis is NUTS-2.</p>
<p><a target="_blank" rel="nofollow" href="https://i2.wp.com/ikashnitsky.github.io/images/170316/fig-01-nuts.png?ssl=1"><img alt="fig1" src="https://i2.wp.com/ikashnitsky.github.io/images/170316/fig-01-nuts.png?w=456&ssl=1" data-recalc-dims="1"></a> <br>
<em>Figure 1. Illustration of the principle of NUTS hierarchical system</em></p>
<p>One of the objectives of NUTS was to provide more or less comparable administrative divisions for all countries of Europe. Nevertheless, in 2013, population figures for single NUTS-2 regions ranged from 28.5 thousands in <em>Aland island</em> (Finland) to almost 12 million in <em>Ile-de-France</em> (Paris and surroundings, France).</p>
<h2>The broken time series</h2>
<p>Quite arbitrary in its essence, territorial division tends to evolve. Changes in administrative boundaries can cause problems for regional analysis as they break the time series and therefore make it harder to analyze trends. Despite this inconvenience, the boundaries of regions actually change quite often based on the needs and interests of local or national governmenta. Eurostat <a target="_blank" rel="nofollow" href="http://ec.europa.eu/eurostat/web/nuts/history">tracks all modifications</a> providing detailed explanations of all the changes that happen between versions of NUTS (figure 2).</p>
<p><a target="_blank" rel="nofollow" href="https://i0.wp.com/ikashnitsky.github.io/images/170316/fig-02-nuts-changes.png?ssl=1"><img alt="fig2" src="https://i0.wp.com/ikashnitsky.github.io/images/170316/fig-02-nuts-changes.png?w=456&ssl=1" data-recalc-dims="1"></a> <br>
<em>Figure 2. Changes in NUTS between versions 2006 and 2010</em></p>
<p>Despite this, Eurostat does not recalculate historic demographic data to match the most recent NUTS version. This means that, for the most recent version of NUTS, there is missing data for all years before the latest administrative change. So researchers have to reconstruct historical data manually to obtain a long time series. Of course, crude assumptions often have to be accepted in order to approximate the population figures for the current regions that did not exist in the past.</p>
<p>To make thing even more complex, Eurostat provides the data only for the latest version of NUTS (at least, I did not work out how to download previous versions). In <a target="_blank" rel="nofollow" href="http://nidi.nl/en/research/al/270rdc">my PhD project</a> I carry out regional analysis for the NUTS-2 regions of European Union. To have the longest possible time series, when I did the data preparation in 2015, I chose the 2010 version of NUTS, on which the regional demographic projection <a target="_blank" rel="nofollow" href="http://ec.europa.eu/eurostat/web/population-demography-migration-projections/population-projections-data">EUROPOP2013</a> is based. For reproducibility, I uploaded the precise versions of the Eurostat data at NUTS-2 level on <a target="_blank" rel="nofollow" href="https://doi.org/10.6084/m9.figshare.3084394">population age structures</a> and <a target="_blank" rel="nofollow" href="https://doi.org/10.6084/m9.figshare.3084418">deaths</a>, as downloaded in 2015, to <a target="_blank" rel="nofollow" href="https://figshare.com/">figshare</a>.</p>
<h2>Denmark</h2>
<p>Some countries had to perform major changes in their systems of territorial division to fit the NUTS standards. <a target="_blank" rel="nofollow" href="http://www.tandfonline.com/doi/abs/10.1080/03003930903560562">The most significant reform happened in Denmark in 2007</a>, where the former 271 municipalities were transformed into the new 98 municipalities. At the same time, NUTS was introduced, so that 98 municipalities were allocated to 11 NUTS-3 regions, which aggregate to 5 NUTS-2 regions. Typically, for a small country, there is only one NUTS-1 region in Denmark, which is the whole country.</p>
<p>As far as I know, there was no official attempt of Eurostat to reconstruct the time series for Denmark before 2007. The typical map of Eurostat for the pre-2007 period shows Denmark as “no data available” country (figure 3).</p>
<p><a target="_blank" rel="nofollow" href="https://i1.wp.com/ikashnitsky.github.io/images/170316/fig-03-nuts-2-life-exp.png?ssl=1"><img alt="fig3" src="https://i1.wp.com/ikashnitsky.github.io/images/170316/fig-03-nuts-2-life-exp.png?w=456&ssl=1" data-recalc-dims="1"></a> <br>
<em>Figure 3. Life expectancy at birth in European NUTS-2 regions, 2006; a screenshot from the Eurostat’s <a target="_blank" rel="nofollow" href="http://ec.europa.eu/eurostat/cache/RCI">interactive data exploratory tool</a></em></p>
<p>Such a data loss is somewhat surprising for a country such as Denmark. It might be quite difficult to match the old and new municipal systems; but it should be relatively easy to re-aggregate the old municipalities into the new (higher level) NUTS regions. That is precisely what I did during my data preparation<sup><a target="_blank" rel="nofollow" href="https://ikashnitsky.github.io/2017/denmark-nuts-reconstruction/#fn:2">1</a></sup> and what I now want to share in this post.</p>
<p>The task is basically to identify which of the old 271 municipalities are located within the modern 11 NUTS-3 regions and to aggregate the municipal data. Then, NUTS-3 data is easily aggregated for the NUTS-2 level. Such a task could have meant working late into the night, but luckily we live in the GIS era. I used GIS to match the old municipalities with the NUTS-3 regions. Here I want to show (with code) how the task can be performed using the amazing and opensource <a target="_blank" rel="nofollow" href="https://cran.r-project.org/">R</a>. Below I show the process of matching old municipalities to the NUTS regions and the process that I used to aggregate population data.</p>
<h2>Data</h2>
<p>The data on the population age structures for the old 271 municipalities of Denmark was downloaded from the <a target="_blank" rel="nofollow" href="https://ikashnitsky.github.io/2017/denmark-nuts-reconstruction/www.statbank.dk/BEF1A">official website of Statistics Denmark</a>. The system only allows you to grab up to 10K cells for unregistered users and up to 100K for registered users. So the process of downloading the data involves some tedious manual manipulations. For the purpose of my phd project, I downloaded the data for the period 2001-2006; but, if needed, the data is available since 1979. The data, downloaded in 2015 and ‘tidied up’ can be found <a target="_blank" rel="nofollow" href="https://ikashnitsky.github.io/doc/misc/nuts2-denmark/BEF1A.csv.gz">here</a>.</p>
<p>I have spent a lot of time trying to find geodata with the boundaries of the old municipalities. Now, coming back to the topic more than 1.5 year later, I failed to identify the original source of the shapefile, though I am pretty sure that it came from <a target="_blank" rel="nofollow" href="http://www.geodatabiblioteket.dk/index.php">here</a> <sup><a target="_blank" rel="nofollow" href="https://ikashnitsky.github.io/2017/denmark-nuts-reconstruction/#fn:3">2</a></sup>. The copy of the shapefile that I used can be found <a target="_blank" rel="nofollow" href="https://ikashnitsky.github.io/doc/misc/nuts2-denmark/kommune2006utf8.tgz">here</a>.</p>
<p>Finally, we need a shapefile of NUTS-3 regions. It can be easily downloaded from <a target="_blank" rel="nofollow" href="http://ec.europa.eu/eurostat/web/gisco/geodata/reference-data/administrative-units-statistical-units/nuts">Eurostat geodata repository</a>. The shapefile that I used is “NUTS_2010_20M_SH.zip”. The selection of the 11 Danish regions can be found <a target="_blank" rel="nofollow" href="https://ikashnitsky.github.io/doc/misc/nuts2-denmark/denmark-nuts3-espg3044.tgz">here</a>.</p>
<p>The projection used for both shapefiles is <a target="_blank" rel="nofollow" href="https://epsg.io/3044">ESPG-3044</a>, the one often used to map Denmark.</p>
<p>Now, the code to prepare the R session and load the data.</p>
<div>
<pre><code># set locale and encoding parameters to read Danish
if(Sys.info()['sysname']==&quot;Linux&quot;){
        Sys.setlocale(&quot;LC_CTYPE&quot;, &quot;da_DK.utf8&quot;)
        danish_ecnoding &lt;- &quot;WINDOWS-1252&quot;
}else if(Sys.info()['sysname']==&quot;Windows&quot;){
        Sys.setlocale(&quot;LC_CTYPE&quot;, &quot;danish&quot;)
        danish_ecnoding &lt;- &quot;Danish_Denmark.1252&quot;
}

# load required packages (install first if needed)
library(tidyverse) # version: 1.0.0
library(ggthemes) # version: 3.3.0
library(rgdal) # version: 1.2-4
library(rgeos) # version: 0.3-21
library(RColorBrewer) # version: 1.1-2
mypal &lt;- brewer.pal(11, &quot;BrBG&quot;)
library(fuzzyjoin) # version: 0.1.2
library(viridis) # version: 0.3.4

# load Denmark pop structures for the old municipalities
df &lt;- read_csv(&quot;https://ikashnitsky.github.io/doc/misc/nuts2-denmark/BEF1A.csv.gz&quot;)

# create a directory for geodata
ifelse(!dir.exists(&quot;geodata&quot;), dir.create(&quot;geodata&quot;), &quot;Directory already exists&quot;)

# download, unzip and read Danish NUTS-3 geodata (31KB)
url_nuts &lt;- &quot;https://ikashnitsky.github.io/doc/misc/nuts2-denmark/denmark-nuts3-espg3044.tgz&quot;
path_nuts &lt;- &quot;geodata/denmark-nuts3-espg3044.tgz&quot;
ifelse(!file.exists(path_nuts), download.file(url_nuts, path_nuts, mode=&quot;wb&quot;), 'file alredy exists')
# If there are problems downloading the data automatically, please download it manually from
# https://ikashnitsky.github.io/doc/misc/nuts2-denmark/denmark-nuts3-espg3044.tgz
untar(tarfile = path_nuts, exdir = &quot;geodata&quot;)

sp_nuts3 &lt;- readOGR(dsn = &quot;geodata/.&quot;, layer = &quot;denmark-nuts3-espg3044&quot;)
gd_nuts3 &lt;- fortify(sp_nuts3, region = &quot;NUTS_ID&quot;) # to the ggplot format


# download, unzip and read Danish old municipal geodata (6.0MB)
url_mun &lt;- &quot;https://ikashnitsky.github.io/doc/misc/nuts2-denmark/kommune2006win1252.tgz&quot;
path_mun &lt;- &quot;geodata/kommune2006win1252.tgz&quot;
ifelse(!file.exists(path_mun), download.file(url_mun, path_mun, mode=&quot;wb&quot;), 'file alredy exists')
# If there are problems downloading the data automatically, please download it manually from
# https://ikashnitsky.github.io/doc/misc/nuts2-denmark/kommune2006utf8.tgz
untar(tarfile = path_mun, exdir = &quot;geodata&quot;)

sp_mun &lt;- readOGR(dsn = &quot;geodata/.&quot;, layer = &quot;kommune2006win1252&quot;, encoding = danish_ecnoding) 
gd_mun &lt;- fortify(sp_mun)

# coordinates of the municipalities
mun_coord &lt;- bind_cols(as.data.frame(coordinates(sp_mun)), sp_mun@data[,1:3]) %>% 
        transmute(long = V1, lat = V2, enhedid, objectid, name = navn)
</code></pre>
</div>
<h2>Spatial matching</h2>
<p>Let’s first have a look at the map.</p>
<div>
<pre><code>ggplot()+
        geom_polygon(data = gd_nuts3, aes(long, lat, group = group), 
                     color = brbg[3], fill = &quot;grey90&quot;, size = 1)+
        geom_point(data = mun_coord, aes(long, lat), 
                   color = brbg[10], size = 1)+
        theme_map()
</code></pre>
</div>
<p><a target="_blank" rel="nofollow" href="https://i1.wp.com/ikashnitsky.github.io/images/170316/fig-04-ref-map.png?ssl=1"><img alt="fig4" src="https://i1.wp.com/ikashnitsky.github.io/images/170316/fig-04-ref-map.png?w=456&ssl=1" data-recalc-dims="1"></a> <br>
<em>Figure 4. Reference map of the old municipalities and NUTS-3 regions of Denmark</em></p>
<p>We can easily see that the boundaries of the municipalities (light blue) are much more precise than that of the NUTS-3 regions (orange/brown). This is not a problem as long as all the centroids of the municipalities fall within the boundaries of the NUTS-3 regions, which seems to be true for all municipalities except for the easternmost one. A quick check reveals that this is <a target="_blank" rel="nofollow" href="https://en.wikipedia.org/wiki/Ertholmene">Christiansø</a>, a tiny fortified island, whose <a target="_blank" rel="nofollow" href="http://www.christiansoe.dk/historien">history</a> goes back to the Middle Ages. It has a special status and <a target="_blank" rel="nofollow" href="http://www.dst.dk/da/Statistik/dokumentation/Nomenklaturer/NUTS">is not included</a> into the NUTS system. For further manipulations, Christiansø can safely merge it with the close-by Bornholm.</p>
<p>To identify which municipalities fall into which NUTS regions, I use the spatial overlap function (<code>over</code>) from <code>sp</code> package. Here I should thank <a target="_blank" rel="nofollow" href="https://www.nhh.no/en/employees/faculty/roger-bivand/">Roger Bivand</a>, a person who made it possible to do any spatial analysis in R.</p>
<div>
<pre><code># municipality coordinates to Spatial
mun_centr &lt;- SpatialPoints(coordinates(sp_mun), proj4string = CRS(proj4string(sp_nuts3)))

# spatial intersection with sp::over
inter &lt;- bind_cols(mun_coord, over(mun_centr, sp_nuts3[,&quot;NUTS_ID&quot;])) %>% 
        transmute(long, lat, objectid,
                  nuts3 = as.character(NUTS_ID),
                  nuts2 = substr(nuts3, 1, 4))
</code></pre>
</div>
<p>Let’s again check visually if the spatial matching worked okay.</p>
<div>
<pre><code>ggplot()+
        geom_polygon(data = gd_mun, aes(long, lat, group = group), 
                     color = brbg[9], fill = &quot;grey90&quot;, size = .1)+
        geom_polygon(data = gd_nuts3, aes(long, lat, group = group), 
                     color = brbg[3], fill = NA, size = 1)+
        geom_point(data = inter, aes(long, lat, color = nuts3), size = 1)+
        geom_point(data = inter[is.na(inter$nuts3),], 
                   aes(long, lat), color = &quot;red&quot;, size = 7, pch = 1)+
        theme_map(base_size = 15)+
        theme(legend.position = c(1, 1),
              legend.justification = c(1, 1))
</code></pre>
</div>
<p><a target="_blank" rel="nofollow" href="https://i2.wp.com/ikashnitsky.github.io/images/170316/fig-05-map-match.png?ssl=1"><img alt="fig5" src="https://i2.wp.com/ikashnitsky.github.io/images/170316/fig-05-map-match.png?w=456&ssl=1" data-recalc-dims="1"></a> <br>
<em>Figure 5. Checking the spatial intersection between the old municipalities and NUTS-3 regions of Denmark</em></p>
<p>Not bad. But there is an “NA” category that represents all the cases where the spatial match failed. How many such cases do we have?</p>
<div>
<pre><code># how many failed cases do we have
sum(is.na(inter$nuts3))
</code></pre>
</div>
<div>
<pre><code>## [1] 3
</code></pre>
</div>
<div>
<pre><code># where the intersection failed
inter[is.na(inter$nuts3),]
</code></pre>
</div>
<div>
<pre><code>##         long     lat objectid nuts3 nuts2
## 23  892474.0 6147918    46399  &lt;NA>  &lt;NA>
## 65  504188.4 6269329   105319  &lt;NA>  &lt;NA>
## 195 533446.8 6312770    47071  &lt;NA>  &lt;NA>
</code></pre>
</div>
<p>As there are only 3 cases, I decided to fix them manually.</p>
<div>
<pre><code># fix the three cases manually
fixed &lt;- inter
fixed[fixed$objectid==&quot;46399&quot;, 4:5] &lt;- c(&quot;DK014&quot;, &quot;DK01&quot;)
fixed[fixed$objectid==&quot;105319&quot;, 4:5] &lt;- c(&quot;DK041&quot;, &quot;DK04&quot;)
fixed[fixed$objectid==&quot;47071&quot;, 4:5] &lt;- c(&quot;DK050&quot;, &quot;DK05&quot;)
</code></pre>
</div>
<p>The final visual check.</p>
<div>
<pre><code>ggplot()+
        geom_polygon(data = gd_mun, aes(long, lat, group = group), 
                     color = brbg[9], fill = &quot;grey90&quot;, size = .1)+
        geom_polygon(data = gd_nuts3, aes(long, lat, group = group), 
                     color = brbg[3], fill = NA, size = 1)+
        geom_point(data = fixed, aes(long, lat, color = nuts3), size = 1)+
        theme_map(base_size = 15)+
        theme(legend.position = c(1, 1),
              legend.justification = c(1, 1))
</code></pre>
</div>
<p><a target="_blank" rel="nofollow" href="https://i1.wp.com/ikashnitsky.github.io/images/170316/fig-06-map-check.png?ssl=1"><img alt="fig6" src="https://i1.wp.com/ikashnitsky.github.io/images/170316/fig-06-map-check.png?w=456&ssl=1" data-recalc-dims="1"></a> <br>
<em>Figure 6. Re-checking the spatial intersection between the old municipalities and NUTS-3 regions of Denmark</em></p>
<p>Now everything seems okay.</p>
<h2>Joining spatial and statistical data (fuzzy join)</h2>
<p>The next task is to join the spatial data and statistical data together. The spatial layer for municipalities does not contain the codes that are used by Statistics Denmark, so I have to match municipalities in the two datasets by their names. This is quite a difficult task. Names can be written slightly differently, there are some special characters in Danish alphabet, and some municipalities may have experienced a change of name. To solve the task most efficiently, I used the ‘Fuzzy String Matching’ approach which is implemented in the <a target="_blank" rel="nofollow" href="https://github.com/dgrtwo/fuzzyjoin"><code>fuzzyjoin</code></a> package by <a target="_blank" rel="nofollow" href="http://varianceexplained.org/about/">David Robinson</a>.</p>
<p>First, I simplify the names in both datasets turning them into lowercase, replacing the character “å” with “aa”, and removing the “Kommune” word in the spatial dataset names. Please note that I downloaded (separately) a small selection from Statistics Denmark to have a <a target="_blank" rel="nofollow" href="https://ikashnitsky.github.io/doc/misc/nuts2-denmark/stat-names-codes.csv.gz">lightweight dataframe</a> with municipal codes and names.</p>
<div>
<pre><code># simplify municipalities names
mun_geo &lt;- mun_coord %>%         
        transmute(name = sub(x = name, &quot; Kommune&quot;, replacement = &quot;&quot;), objectid) %>% 
        mutate(name = gsub(x = tolower(name), &quot;å&quot;, &quot;aa&quot;))

mun_stat &lt;- read.csv2(&quot;https://ikashnitsky.github.io/doc/misc/nuts2-denmark/stat-codes-names.csv&quot;, 
                      fileEncoding = danish_ecnoding) %>% 
        select(name) %>% 
        separate(name, into = c(&quot;code&quot;, &quot;name&quot;), sep = &quot; &quot;, extra = &quot;merge&quot;) %>% 
        mutate(name = gsub(&quot;\\s*\\([^\\)]+\\)&quot;, &quot;&quot;, x = name)) %>% 
        mutate(name = gsub(x = tolower(name), &quot;å&quot;, &quot;aa&quot;))
</code></pre>
</div>
<p>Let’s try fuzzy join.</p>
<div>
<pre><code># first attempt
fuz_joined_1 &lt;- regex_left_join(mun_geo, mun_stat, by = &quot;name&quot;)
</code></pre>
</div>
<p>The resulting dataframe has 278 rows instead of 271. That means that for some municipalities in the spatial dataset there was more than one match. Let’s identify them.</p>
<div>
<pre><code># identify more that 1 match (7 cases) and select which to drop
fuz_joined_1 %>% group_by(objectid) %>% mutate(n = n()) %>% filter(n > 1)
</code></pre>
</div>
<div>
<pre><code>## Source: local data frame [14 x 5]
## Groups: objectid [7]
## 
##         name.x objectid  code      name.y     n
##          &lt;chr>    &lt;dbl> &lt;chr>       &lt;chr> &lt;int>
## 1       haslev   105112   313      haslev     2
## 2       haslev   105112   403       hasle     2
## 3  brønderslev    47003   739       rønde     2
## 4  brønderslev    47003   805 brønderslev     2
## 5    hirtshals    47037   817        hals     2
## 6    hirtshals    47037   819   hirtshals     2
## 7      rønnede    46378   385     rønnede     2
## 8      rønnede    46378   407       rønne     2
## 9     hvidebæk    46268   317    hvidebæk     2
## 10    hvidebæk    46268   681     videbæk     2
## 11    ryslinge    46463   477    ryslinge     2
## 12    ryslinge    46463   737          ry     2
## 13     aarslev    46494   497     aarslev     2
## 14     aarslev    46494   861        aars     2
</code></pre>
</div>
<p>So, for 7 municipalities, two matches were found. I will drop the imperfect match variants in the next iteration of fuzzy join.</p>
<p>The other issue is the municipalities for which no match was found in that statistical data.</p>
<div>
<pre><code># show the non-matched cases
fuz_joined_1 %>% filter(is.na(code))
</code></pre>
</div>
<div>
<pre><code>##              name.x objectid code name.y
## 1              faxe   105120 &lt;NA>   &lt;NA>
## 2 nykøbing falsters    46349 &lt;NA>   &lt;NA>
## 3       herstederne    46101 &lt;NA>   &lt;NA>
</code></pre>
</div>
<p>As there are only three such cases, I corrected them manually in the spatial data to match the statistical data. There are two cases of a difference in the way the name of municipality are written and <a target="_blank" rel="nofollow" href="http://albertslund.lokalavisen.dk/fra-herstederne-til-albertslund-/20131017/artikler/710179831">one case of name change</a>.</p>
<div>
<pre><code># correct the 3 non-matching geo names
mun_geo_cor &lt;- mun_geo

mun_geo_cor[mun_geo_cor$name==&quot;faxe&quot;, &quot;name&quot;] &lt;- &quot;fakse&quot;
mun_geo_cor[mun_geo_cor$name==&quot;nykøbing falsters&quot;, &quot;name&quot;] &lt;- &quot;nykøbing f.&quot;
mun_geo_cor[mun_geo_cor$name==&quot;herstederne&quot;, &quot;name&quot;] &lt;- &quot;albertslund&quot;
</code></pre>
</div>
<p>Now the second attempt to match the datasets (spatial dataset is corrected).</p>
<div>
<pre><code># second attempt
fuz_joined_2 &lt;- regex_left_join(mun_geo_cor, mun_stat, by = &quot;name&quot;)

# drop non-perfect match
fuz_joined_2 &lt;- fuz_joined_2 %>% 
        group_by(objectid) %>% 
        mutate(n = n()) %>% 
        ungroup() %>% 
        filter(n &lt; 2 | name.x==name.y)

fuz_joined_2 &lt;- fuz_joined_2 %>% transmute(name = name.x, objectid, code)
</code></pre>
</div>
<p>The output looks perfect. Now, the last step – using the matched “objectid” field, I will finally attach the NUTS data to statistical codes.</p>
<div>
<pre><code># finally, attach the NUTS info to matched table
key &lt;- left_join(fuz_joined_2, fixed, &quot;objectid&quot;)
</code></pre>
</div>
<h2>Aggregate old municipal data to NUTS levels</h2>
<p>The previous manipulations yielded a dataframe that links statistical codes of the old municipalities with the corresponding NUTS regions. The last thing that has to be done is aggregation. I will attach the “key” dataset to a statistical dataset and aggregate the data at NUTS-3 and NUTS-2 levels.</p>
<div>
<pre><code># finally, we only need to aggregate the old stat data
df_agr &lt;- left_join(key, df, &quot;code&quot;) %>% 
        filter(!is.na(name)) %>% 
        gather(&quot;year&quot;, &quot;value&quot;, y2001:y2006)

df_nuts3 &lt;- df_agr %>% 
        group_by(year, sex, age, nuts3) %>% 
        summarise(value = sum(value)) %>% 
        ungroup()

df_nuts2 &lt;- df_agr %>% 
        group_by(year, sex, age, nuts2) %>% 
        summarise(value = sum(value)) %>% 
        ungroup()
</code></pre>
</div>
<p>Let’s now calculate the shares of working age population in Danish NUTS-3 regions in 2001 and map the information.</p>
<div>
<pre><code># total population in 2001 by NUTS-3 regions
tot_01 &lt;- df_nuts3 %>% 
        filter(year==&quot;y2001&quot;) %>% 
        group_by(nuts3) %>% 
        summarise(tot = sum(value, na.rm = TRUE)) %>% 
        ungroup()

# working-age population in 2001 by NUTS-3 regions
working_01 &lt;- df_nuts3 %>% 
        filter(year==&quot;y2001&quot;, age %in% paste0(&quot;a0&quot;, 15:64)) %>% 
        group_by(nuts3) %>% 
        summarise(work = sum(value, na.rm = TRUE)) %>% 
        ungroup()

# calculate the shares of working age population
sw_01 &lt;- left_join(working_01, tot_01, &quot;nuts3&quot;) %>% 
        mutate(sw = work / tot * 100)
</code></pre>
</div>
<div>
<pre><code># map the shares of working age population in 2001 by NUTS-3 regions
ggplot()+
        geom_polygon(data = gd_nuts3 %>% left_join(sw_01, c(&quot;id&quot; = &quot;nuts3&quot;)),
                     aes(long, lat, group = group, fill = sw), 
                     color = &quot;grey50&quot;, size = 1) +
        scale_fill_viridis()+
        theme_map(base_size = 15)+
        theme(legend.position = c(1, 1),
              legend.justification = c(1, 1))
</code></pre>
</div>
<p><a target="_blank" rel="nofollow" href="https://i1.wp.com/ikashnitsky.github.io/images/170316/fig-07-map-sw.png?ssl=1"><img alt="fig7" src="https://i1.wp.com/ikashnitsky.github.io/images/170316/fig-07-map-sw.png?w=456&ssl=1" data-recalc-dims="1"></a> <br>
<em>Figure 7. The share of working age (15-64) population by NUTS-3 regions of Denmark in 2001</em></p>
<p>The result (thankfully!) looks realistic, with higher shares of the working-age population in the capital region, and in other regions that have relatively big cities.</p>
<hr>
<h3><a target="_blank" rel="nofollow" href="https://demotrends.wordpress.com/2017/03/16/working-with-spatial-data-to-generate-a-consistent-demographic-time-series/">This post is written for Demotrends</a></h3>
<hr>
<div>
<ol>
<li>
<p>I have spent quite some time searching if someone else did the job before me and failed to find. <a target="_blank" rel="nofollow" href="https://ikashnitsky.github.io/2017/denmark-nuts-reconstruction/#fnref:2">↩</a></p>
</li>
<li>
<p>There is a note on the website saying that, due to a planned change in the structure of the website, there might be some problems with data accuisition. I failed to download the geodata on 2017-02-23. <a target="_blank" rel="nofollow" href="https://ikashnitsky.github.io/2017/denmark-nuts-reconstruction/#fnref:3">↩</a></p>
</li>
</ol>
</div>
<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://ikashnitsky.github.io/2017/denmark-nuts-reconstruction/"> Ilya Kashnitsky</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" rel="nofollow" href="https://www.r-project.org/">R</a> news and <a title="R tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/tutorial">tutorials</a> on topics such as: <a title="Data science" rel="nofollow" href="https://www.r-bloggers.com/search/data%20science">Data science</a>, <a title="Big Data" rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data">Big Data, <a title="R jobs" rel="nofollow" href="https://www.r-users.com/">R jobs</a>, visualization (<a title="ggplot and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2">ggplot2</a>, <a title="Boxplots using lattice and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/boxplot">Boxplots</a>, <a title="Maps and gis" rel="nofollow" href="https://www.r-bloggers.com/search/map">maps</a>, <a title="Animation in R" rel="nofollow" href="https://www.r-bloggers.com/search/animation">animation</a>), programming (<a title="RStudio IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/RStudio">RStudio</a>, <a title="Sweave and literate programming" rel="nofollow" href="https://www.r-bloggers.com/search/sweave">Sweave</a>, <a title="LaTeX in R" rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX">LaTeX</a>, <a title="SQL and databases" rel="nofollow" href="https://www.r-bloggers.com/search/SQL">SQL</a>, <a title="Eclipse IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/eclipse">Eclipse</a>, <a title="git and github, Version Control System" rel="nofollow" href="https://www.r-bloggers.com/search/git">git</a>, <a title="Large data in R using Hadoop" rel="nofollow" href="https://www.r-bloggers.com/search/hadoop">hadoop</a>, <a title="Web Scraping of google, facebook, yahoo, twitter and more using R" rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping">Web Scraping</a>) statistics (<a title="Regressions and ANOVA analysis tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/regression">regression</a>, <a title="principal component analysis tutorial" rel="nofollow" href="https://www.r-bloggers.com/search/PCA">PCA</a>, <a title="Time series" rel="nofollow" href="https://www.r-bloggers.com/search/time+series">time series</a>, <a title="finance trading" rel="nofollow" href="https://www.r-bloggers.com/search/trading">trading</a>) and more...
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/vbqUh2C3_dw"></a></div>