Final project - Intro to R

Created by Balint Thaler

Introduction

This is an R Markdown document for CEU’s Intro to R course.

For this project the dataset of the TidyTuesday Project will be used. Specifically the one from 2022.08.22 about refugees. Furthermore, I will use data from the UN on Human Development Index (HDI) to check if the flow of refugees follows an intuitive idea, that is from lower HDI countries to higher HDI countries.

The respective GitHub repo containing the data files and the ReadMe can be accessed here: https://github.com/rfordatascience/tidytuesday/tree/master/data/2023/2023-08-22

Let’s install the required packages - which are data.table, ggplot2 and dplyr.

library(data.table)
library(ggplot2)
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:data.table':
## 
##     between, first, last
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union

Data loading and cleaning

Let’s load the data and inspect it.

refugees <- read.csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2023/2023-08-22/population.csv')
head(refugees, 5)
##   year               coo_name coo coo_iso    coa_name coa coa_iso refugees
## 1 2010            Afghanistan AFG     AFG Afghanistan AFG     AFG        0
## 2 2010 Iran (Islamic Rep. of) IRN     IRN Afghanistan AFG     AFG       30
## 3 2010                   Iraq IRQ     IRQ Afghanistan AFG     AFG        6
## 4 2010               Pakistan PAK     PAK Afghanistan AFG     AFG     6398
## 5 2010                  Egypt ARE     EGY     Albania ALB     ALB        5
##   asylum_seekers returned_refugees   idps returned_idps stateless    ooc oip
## 1              0                 0 351907          3366         0 838250  NA
## 2             21                 0      0             0         0      0  NA
## 3              0                 0      0             0         0      0  NA
## 4              9                 0      0             0         0      0  NA
## 5              0                 0      0             0         0      0  NA
##   hst
## 1  NA
## 2  NA
## 3  NA
## 4  NA
## 5  NA

Let’s convert to data.table, filter for a singular year of 2018 and drop redundant columns of country codes. I will focus on refugees and internally displaced people only.

ref_dt <- data.table(refugees)
ref_dt <- ref_dt[year == 2018]
ref_dt <- ref_dt[, c("coo", "coa", "asylum_seekers", "returned_refugees", "returned_idps", "stateless", "ooc", "oip", "hst") := NULL]

Let’s download another dataset from the UN’s World Development Report website which contains data on the countries’ Human Development Index (HDI).

hdi <- read.csv('https://hdr.undp.org/sites/default/files/2021-22_HDR/HDR21-22_Composite_indices_complete_time_series.csv')
hdi_dt <- data.table(hdi)
dim(hdi_dt)
## [1]  206 1008

This dataset is massive and contains a number of unnecessary columns. Let’s create a new data.table with only the relevant columns.

hdi_clean <- hdi_dt[, c("iso3", "country", "hdicode", "hdi_2018")]
head(hdi_clean, 5)
##    iso3              country   hdicode hdi_2018
## 1:  AFG          Afghanistan       Low    0.483
## 2:  AGO               Angola    Medium    0.595
## 3:  ALB              Albania      High    0.806
## 4:  AND              Andorra Very High    0.872
## 5:  ARE United Arab Emirates Very High    0.909

Let’s merge the two data.tables on the country codes.

total_data <- ref_dt[hdi_clean, on = .(coo_iso = iso3)]

Now we have the HDI indexes of the coos (country of origin). Let’s also add them for the coa (country of asylum).

hdi_coa <- hdi_clean[, c('iso3', 'hdicode', 'hdi_2018')]
setnames(hdi_coa, c("iso3", "hdicode", "hdi_2018"), c("iso3_coa", "hdicode_coa", "hdi_2018_coa"))
total_data <- total_data[hdi_coa, on = .(coa_iso = iso3_coa)]
head(total_data, 5)
##    year               coo_name coo_iso    coa_name coa_iso refugees    idps
## 1: 2018            Afghanistan     AFG Afghanistan     AFG        0 2106893
## 2: 2018             Bangladesh     BGD Afghanistan     AFG        0       0
## 3: 2018 Iran (Islamic Rep. of)     IRN Afghanistan     AFG       34       0
## 4: 2018               Pakistan     PAK Afghanistan     AFG    72194       0
## 5: 2018             Tajikistan     TJK Afghanistan     AFG        0       0
##                       country hdicode hdi_2018 hdicode_coa hdi_2018_coa
## 1:                Afghanistan     Low    0.483         Low        0.483
## 2:                 Bangladesh  Medium    0.635         Low        0.483
## 3: Iran (Islamic Republic of)    High    0.787         Low        0.483
## 4:                   Pakistan     Low    0.545         Low        0.483
## 5:                 Tajikistan  Medium    0.671         Low        0.483

Let’s add one more column on the total number of people affected and drop na values.

total_data$total <- total_data$refugees + total_data$idps
total_data <- na.omit(total_data)

Now the data is ready to be analysed.

Data analysis

First let’s take a look at the top10 of number of refugees by country of origin.

top10_coo <- head(total_data[,sum(refugees), by = coo_name][order(-V1)], 10)
library(scales)

ggplot(top10_coo, aes(coo_name, V1)) + geom_col() + theme_classic() + coord_flip() + ylab("Number of refugees") + xlab('') + scale_y_continuous(labels = scales::comma) + labs(title ="Top 10 countries by number of refugees")

The top 10 countries on the list have millions of refugees that have left these places. The conflicts in Syria, South Sudan and Afghanistan are clearly visible in these figures.

Let’s see the same for country of asylum.

top10_coa <- head(total_data[,sum(refugees), by = coa_name][order(-V1)], 10)
ggplot(top10_coa, aes(coa_name, V1)) + geom_col() + 
  theme_classic() + coord_flip() + ylab("Number of incoming refugees") + xlab('') +
  scale_y_continuous(labels = scales::comma) + 
  labs(title ="Top 10 asylum countries")

One would expect that given the media coverage on the topic the developed countries would have the highest influx of refugees, however it seems that only Germany made it to the top 10. Most countries seem to be the neighbors of or close to the countries from the previous chart.

Let’s see the figures by HDI categories.

ref_by_hdi <- total_data[!hdicode == "", sum(refugees), by = hdicode]
ref_by_hdi
##      hdicode      V1
## 1:       Low 8962431
## 2:    Medium 8526297
## 3:      High 1282059
## 4: Very High  217907

It is clearly visible, that countries belonging in the Low or Medium HDI scores have much higher refugee numbers. Let’s visualise that in more details by looking at the pairwise HDI figures.

scatter_data1 <- total_data[!hdi_2018 == "" & !hdicode_coa == "", weighted.mean(hdi_2018, w = refugees), by = country]
scatter_data2 <- total_data[!hdi_2018 == "" & !hdicode_coa == "", weighted.mean(hdi_2018_coa, w = refugees), by = country]
scatter_data3 <- scatter_data1[scatter_data2, on = .(country = country)]
scatter_data <- scatter_data3[total_data[refugees > 1000, sum(refugees), by = country], on =.(country = country)]

colnames(scatter_data) <- c("country", "hdi_origin", "avg_hdi_target", "refugees") 
scatter_data[total_data, on = 'country', hdicode := i.hdicode] 

ggplot(scatter_data, aes(x= hdi_origin, y=avg_hdi_target)) + geom_point(aes(size = refugees, color = hdicode)) +
  theme_classic() + geom_smooth(se = FALSE) +
  xlab("HDI of COO") + ylab("Average COA HDI") + 
  labs(size = "Number of refugees", color = "HDI category", title = "Number of refugees by COO and COA HDI - above 1000") + 
  scale_size_continuous(labels=comma) + 
  scale_color_brewer(breaks=c("Low","Medium","High", "Very High"), palette = "Spectral") +
  geom_abline(intercept = 0, slope = 1, linewidth = 0.5)
## `geom_smooth()` using method = 'loess' and formula = 'y ~ x'

We can observe a number of interesting patterns on this chart:

  • Most dots are above the 45 degree line, so refugees generally go to higher HDI countries
  • The higher the “source” country’s HDI, the higher the target country’s HDI as well - this also is a consequence of the previous point.
  • The HDI difference between the origin and target country is flattening out if the origin country’s HDI if higher than 0.6
  • There are relatively few countries that “create” the majority of the refugees (seen in the larger dot sizes)

Now let’s look at the internally displaced figures.

idps1 <- aggregate(hdi_2018 ~ country, data = total_data, FUN = mean, na.rm = TRUE)
idps2 <- aggregate(idps ~ country, data = total_data, FUN = sum, na.rm = TRUE)
idps_data <- merge(idps1, idps2, on = "country")

ggplot(idps_data, aes(idps)) + geom_histogram() + xlab("Nr of internally displaced") + ylab("Nr of countries") + theme_classic() + scale_x_continuous(labels = scales::comma)
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

Most countries have 0 internally displaced people, so let’s filter them out and check out the histogram.

ggplot(idps_data[idps_data$idps>0,], aes(idps)) + geom_histogram() + xlab("Nr of internally displaced") + ylab("Nr of countries") + theme_classic() + scale_x_continuous(labels = scales::comma)
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

Once again we see that the vast majority of the internally displaced people are in a few countries. Let’s see who are in the top 10.

top10_idps <- head(total_data[,sum(idps), by = coo_name][order(-V1)], 10)
top10_idps
##                   coo_name      V1
##  1:               Colombia 7816473
##  2:       Syrian Arab Rep. 6183920
##  3: Dem. Rep. of the Congo 4516866
##  4:               Ethiopia 2615800
##  5:                Nigeria 2167925
##  6:                  Yemen 2144719
##  7:            Afghanistan 2106893
##  8:            South Sudan 1878154
##  9:                  Sudan 1864195
## 10:                   Iraq 1802832

We see some match with the list of top 10 by refugee numbers. This confirms that the situations in these countries force people to flee - often, but not only abroad. Let’s see which countries are affected by the refugee crisis the most by focusing on the total number of internally displaced people and refugees.

crisis <- total_data[, sum(total), by = country][order(-V1)][V1>100000]
dim(crisis)
## [1] 34  2

There were 34 countries where the refugee crisis in 2018 has displaced at least 100,000 people (internally or abroad). Let’s see how this changes per HDI category.

crisis <- total_data[, sum(total), by = country][order(-V1)]
crisis[total_data, on = 'country', hdicode := i.hdicode] 
crisis <- crisis[, .(country, V1, hdicode)]

ggplot(crisis[, sum(V1), by = hdicode], aes(x=reorder(hdicode, -V1), y = V1)) + geom_col() + theme_bw() + xlab("HDI groups") + ylab("Total people affected") + scale_y_continuous(labels = scales::comma) + labs(title = "Number of affected by HDI groups")

Not surprisingly we see that lower HDI is associated with more displaced people. Let’s check this on a continuous scale.

crisis[total_data, on = 'country', hdi_2018 := i.hdi_2018] 
ggplot(crisis, aes(x=hdi_2018, y = V1)) + geom_point() + theme_bw() + geom_smooth(se=FALSE) + xlab("HDI") + ylab("Total people affected") + scale_y_continuous(labels = scales::comma) + labs(title = "Number of affected by HDI groups") + facet_wrap(~factor(hdicode,levels=c('Low','Medium','High','Very High')), scales = 'free')
## `geom_smooth()` using method = 'loess' and formula = 'y ~ x'

We observe rather different patterns in different HDI categories but most countries in the medium, high or very high categories are (close to) 0. While in the low category we see multiple countries in the millions. It seems though that there is no very clear association between HDI and total number of affected. It is generally likely that any crisis is more likely in low HDI countries but this is naturally not a causal relationship.

Conclusion

It seems that refugees do follow the higher standard of living (as measured by the HDI) to some extent, however we have also seen that the inflow of the refugees is highest mostly in countries that are close by to the conflicts. This suggest that refugees often go to the nearest safe place without much regard to the standard of living in the country. Media coverage often does not include the fact that these neighbor countries have had a much larger share from the challenge of managing millions of refugees.