# Lootable resources / natural resources
# Based on code by Jay Ulfelder
# Source-URL: https://github.com/ulfelder/cpg-statrisk-2014/blob/master/wdi.R

# This script uses the 'WDI' package in R to download selected data from the
# latest version of the World Bank's World Development Indicators To modify 
# the variables selected, you need to make changes to 'wdilist' and the 
# commands that follow "Subset" and "Rename variables".

wdilist <- c("NY.ADJ.DFOR.GN.ZS", # Adjusted savings: forest depletion (% of GNI)
             "NY.ADJ.DMIN.GN.ZS", # Adjusted savings: mineral depletion (% of GNI)
             "NY.ADJ.DNGY.GN.ZS") # Adjusted savings: energy depletion (% of GNI)

# Extract latest version of desired variables from WDI.
wdi <- WDI(country="all", indicator = wdilist, extra = FALSE,
           start = 1989, end = 2009)

wdi$actorid <- countrycode(wdi$iso2c, "iso2c", "cown", warn = T)
wdi$actorid[wdi$country=="Kosovo"] <- 347 # Kosovo 
wdi$actorid[wdi$country=="Serbia"] <- 345 # Serbia (Yugoslavia)
wdi$actorid[wdi$country=="South Sudan"] <- 626 # South Sudan (to be sure that it does not match Sudan)
wdi$actorid[wdi$country=="Yemen, Rep."] <- 678 # used in SVAC for Yemen (In CoW: Yemen Arab Republic!)
wdi$actorid[wdi$country=="South Africa"] <- 560 # South Africa
wdi$actorid[wdi$country=="Zimbabwe"] <- 552 # Zimbabwe

# Subset.
wdi <- subset(wdi, is.na(actorid)==FALSE, 
              select=c(actorid, year, NY.ADJ.DNGY.GN.ZS, NY.ADJ.DMIN.GN.ZS, NY.ADJ.DFOR.GN.ZS ) )

# Rename variables.
names(wdi) <- c("actorid", "year", "wdi.energy", "wdi.minerals", "wdi.forest" )

# Join to Master dataset
Master <- join(Master, wdi, by = c("actorid", "year"), type = "left", match = "all")

# Write out as .csv.
# write.csv(wdi, "Daten/World Bank WDI/natural_resources.csv", row.names=FALSE)


## ------------------- ##
## Ross Oil & Gas Data ##
## ------------------- ##

ross <- read.csv("Daten/Ross Oil & Gas Data/Ross Oil & Gas Data 1932-2011.tab", header = T, sep = "\t", as.is = T)

ross$actorid <- countrycode(ross$cty_name, "country.name", "cown", warn = T)
ross$actorid[ross$cty_name=="Czechoslovakia"] <- 315 # Czechoslovakia (ceases to exist on 31/12/1992)
ross$actorid[ross$cty_name=="Slovak Republic"] <- 317 # Slovakia

ross <- subset(ross, subset = is.na(actorid)==FALSE & year >= 1989 & year <= 2009,
              select=c(actorid, year, oil_production, gas_production))

Master <- join(Master, ross, by = c("actorid", "year"), type = "left", match = "all")


## CLEAN WORKSPACE
rm(wdi, wdilist, ross)
