This repository has been archived by the owner on Feb 21, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tidy.r
214 lines (199 loc) · 7.81 KB
/
tidy.r
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
#!/usr/bin/env Rscript --vanilla
# download and combine gapminder and berkeley earth data
# james goldie ('rensa'), august 2017
library(RCurl)
library(rvest)
library(tidyverse)
library(magrittr)
library(stringr)
library(fuzzyjoin)
filter = dplyr::filter # this is going to kill me one day
source('util.r')
# constants
on_url = 'https://raw.githubusercontent.com/open-numbers/'
berk_url = 'http://berkeleyearth.lbl.gov/auto/Regional/TAVG/Text/'
year_start = 1900
year_end = 2012
# create data directory if it's missing
if(!dir.exists('data'))
{
dir.create('data')
}
# download gapminder files if they're missing
gap_files = data_frame(
repo = c(
'ddf--gapminder--population',
'ddf--cait--historical_emissions',
'ddf--gapminder--gdp_per_capita_cppp',
'ddf--gapminder--population',
'ddf--cait--historical_emissions'),
file = c(
'ddf--entities--geo--country.csv',
'ddf--entities--country.csv',
'ddf--datapoints--gdp_per_capita_cppp--by--geo--time.csv',
'ddf--datapoints--population--by--country--year.csv',
paste0(
'ddf--datapoints--total_co2_emissions_excluding_land_use_change_and_',
'forestry_mtco2--by--country--year.csv')),
remote_url = paste0(on_url, repo, '/master/', file),
local_path = paste0('data/gapminder/', file))
gap_files_to_download = which(!file.exists(gap_files$local_path))
if (length(gap_files_to_download) > 0)
{
message(run.time(), ' downloading missing gapminder data')
mapply(download.file,
gap_files$remote_url[gap_files_to_download],
destfile = gap_files$local_path[gap_files_to_download])
} else
{
message(run.time(), ' found all gapminder data')
}
# load and tidy gapminder country code maps
message(run.time(), ' loading and tidying any missing gapminder data')
geo_gap =
read_csv('data/gapminder/ddf--entities--geo--country.csv', na = c('')) %>%
select(country, gapminder_list, alternative_1, alternative_2,
iso3166_1_alpha2, world_6region, income_groups) %>%
rename(name = gapminder_list)
geo_co2 =
read_csv('data/gapminder/ddf--entities--country.csv', na = c('')) %>%
rename(name_co2 = name)
# load and tidy gapminder data sets
gdp_percap =
read_csv(paste0(
'data/gapminder/',
'ddf--datapoints--gdp_per_capita_cppp--by--geo--time.csv'), na = c('')) %>%
rename(country = geo, year = time, gdppc = gdp_per_capita_cppp) %>%
filter(year >= year_start & year <= year_end) %>%
inner_join(geo_gap) %>%
select(name, year, gdppc, alternative_1, alternative_2,
iso3166_1_alpha2, world_6region, income_groups) %>%
# namibia is a pain in the butt because of its code is NA
mutate(iso3166_1_alpha2 = case_when(
name == 'Namibia' ~ 'NA',
TRUE ~ iso3166_1_alpha2)) %>%
mutate(world_6region = recode(world_6region,
'europe_central_asia' = 'Europe + Central Asia',
'south_asia' = 'South Asia',
'sub_saharan_africa' = 'Sub-Saharan Africa',
'america' = 'America',
'middle_east_north_africa' = 'Middle East + North Africa',
'east_asia_pacific' = 'East Asia + Pacific'))
pop =
read_csv(paste0(
'data/gapminder/',
'ddf--datapoints--population--by--country--year.csv'), na = c('')) %>%
filter(year >= year_start & year <= year_end) %>%
inner_join(geo_gap) %>%
select(name, year, population, alternative_1, alternative_2,
iso3166_1_alpha2)
co2 =
read_csv(paste0(
'data/gapminder/','ddf--datapoints--total_co2_emissions_excluding_land_use_change_','and_forestry_mtco2--by--country--year.csv'), na = c('')) %>%
rename(
co2 = total_co2_emissions_excluding_land_use_change_and_forestry_mtco2) %>%
filter(year >= year_start & year <= year_end) %>%
inner_join(geo_co2) %>%
select(name_co2, year, co2)
# combine gapminder datasets,
# rank countries each year by their gdp per capita
# calculation global pop, pop fraction and number of poorer people each year
message(run.time(), ' combining gapminder data')
gapdata = gdp_percap %>% inner_join(pop)
gapdata =
bind_rows(list(
co2 %>% inner_join(gapdata,
by = c('name_co2' = 'name', 'year' = 'year')),
co2 %>% inner_join(gapdata,
by = c('name_co2' = 'alternative_1', 'year' = 'year')),
co2 %>% inner_join(gapdata,
by = c('name_co2' = 'alternative_2', 'year' = 'year')))) %>%
select(-name, -alternative_1, -alternative_2) %>%
rename(name = name_co2)
gapdata$flag_emoji =
iso_to_emoji_unicode(gapdata$iso3166_1_alpha2)
gapdata$flag_file_basename =
iso_to_emoji_ascii(gapdata$iso3166_1_alpha2)
gapdata %<>%
mutate(annual_devrank = ave(gdppc, year, FUN = rank)) %>%
group_by(year) %>%
arrange(annual_devrank) %>%
mutate(
pop_global = sum(population),
pop_fraction = population / pop_global,
pop_poorer = cumsum(population) - population,
pop_poorer_fraction = pop_poorer / pop_global) %>%
ungroup() %>%
group_by(name) %>%
arrange(year) %>%
mutate(co2_cum = cumsum(co2)) %>%
ungroup() %>%
mutate(., emission_id = group_indices(., name, year))
# scrape a list of available berkeley earth country temp data files and
# match them fuzzily against gapdata countries
message(run.time(), ' scraping list of available berkeley temperature data')
berk_files =
data_frame(
filename = berk_url %>% read_html %>% html_nodes('a') %>% html_text) %>%
slice(-(1:6)) %>%
mutate(
name_lowercase = str_replace(filename, '-TAVG-Trend.txt', '')) %>%
# drop some tricky rows (utf escaping problems? TODO)
filter(!name_lowercase %in% c('pará', 'côte-d\'ivoire'))
# okay, now do a loose fuzzy match between gapminder names and berkeley names and choose the best reuslts for each gapminder file. this strips out whitespace and punctuation first, as they bias the fuzzy matching algorithm
message(run.time(), ' fuzzy joining gapminder and berkeley country names')
gapdata_names = data_frame(
name = unique(gapdata$name),
name_nopunc = str_to_lower(str_replace_all(name, ' ', '')))
name_matches =
data_frame(
name_lowercase = unique(berk_files$name_lowercase),
name_lowercase_nopunc = str_replace_all(name_lowercase, '-', ''))
name_matches %<>%
stringdist_inner_join(gapdata_names, by = c(name_lowercase_nopunc = 'name_nopunc'),
max_dist = 5, distance_col = 'match_dist') %>%
group_by(name) %>%
top_n(-1, wt = match_dist) %>%
ungroup() %>%
filter(match_dist <= 1) %>%
select(name, name_lowercase, match_dist)
# now bolt the matches onto the berkeley list and the gapminder data
berk_files %<>% inner_join(name_matches, by = 'name_lowercase')
gapdata %<>% inner_join(name_matches, by = 'name')
# TODO - got about 160 countries between all datasets at this point
# might need to fiddle with the strings to get the edge cases...
# download berkeley files, tag each one with the country and bind them together
temp =
lapply(
berk_files$name_lowercase, function(x)
{
if (!file.exists(paste0('data/berkeley/', x, '-TAVG-Trend.txt')))
{
message(run.time(), ' downloading berkeley temperature data for ', x)
download.file(paste0(berk_url, x, '-TAVG-Trend.txt'),
destfile = paste0('data/berkeley/', x, '-TAVG-Trend.txt'))
} else
{
message(run.time(), ' found berkeley temperature data for ', x)
}
read_table2(
paste0('data/berkeley/', x, '-TAVG-Trend.txt'),
comment = '%', skip = 1, col_types = 'ii--dd------',
col_names = FALSE) %>%
mutate(name_lowercase = x)
}) %>%
bind_rows %>%
rename(year = X1, month = X2, temp = X5, temp_unc = X6) %>%
filter(year >= year_start & year <= year_end & month == 6) %>%
select(-month) %>%
mutate(
temp_min = temp - temp_unc,
temp_max = temp + temp_unc) %>%
inner_join(name_matches, by = 'name_lowercase')
# finally, join the datasets together
message(run.time(), ' joining berkeley and gapminder data')
all_data =
inner_join(gapdata, temp,
by = c('name', 'name_lowercase', 'year', 'match_dist'))
write_csv(all_data, 'data/gapminder-berkeley-tidy.csv')
message(run.time(), ' done!')