-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path06-pipeline.Rmd
362 lines (280 loc) · 10.2 KB
/
06-pipeline.Rmd
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
---
editor_options:
markdown:
wrap: 72
---
# The pipeline
- RStudio Environment. Let's rearrange the panel layout:
![Tools\>Global Options...](images/img_panel00.png)
![Pane Layout](images/img_panel01.png)
## Essential data management and folder structure
``` {sh, eval = FALSE}
├── config.R
├── data_derived
│ ├── Australia_SDG_14.csv
│ ├── sdg_14.csv
│ ├── sdg_14_unclos_map.csv
│ └── sdg_3_1_2.csv
├── data_provided
│ ├── country-to-region-mapping.csv
│ ├── Ocean Accounts Diagnostic Tool_formatted.pdf
│ ├── SDG-DSD-Guidelines.pdf
│ ├── SDG.xlsx
│ └── SDG_Updateinfo.xlsx
├── DatSciTrain_SDGs_API_R.Rproj
├── figures_and_tables
│ ├── fig2.png
│ └── sdg14_Australia.docx
├── LICENSE
├── R
│ ├── do_clean.R
│ ├── do_get_sdg_api.R
│ ├── do_map.R
│ ├── do_plot.R
│ └── do_tab_Australia.R
├── README.md
└── run.R
```
## config.R
```{r, eval = FALSE}
# packages
if (!require(data.table)) {
install.packages("data.table")
library(data.table)
}
if (!require(ggplot2)) {
install.packages("ggplot2")
library(ggplot2)
}
if (!require(sf)) {
install.packages("sf")
library(sf)
}
if (!require(RColorBrewer)) {
install.packages("RColorBrewer")
library(RColorBrewer)
}
if (!require(rnaturalearth)) {
install.packages("rnaturalearth")
library(rnaturalearth)
}
if (!require(rnaturalearthdata)) {
install.packages("rnaturalearthdata")
library(rnaturalearthdata)
}
## set folder names
folder_names <- c("data_derived", "data_provided", "figures_and_tables")
for (folder_name in folder_names) {
if (!dir.exists(folder_name)) {
dir.create(folder_name)
cat("Folder", folder_name, "created.\n")
} else {
cat("Folder", folder_name, "already exists.\n")
}
}
## source functions
file_list <- list.files(path = "R", pattern = "\\.R$", full.names = TRUE)
# Source each .R file
for (file in file_list) {
source(file)
}
```
## run.R
```{r, eval = FALSE}
source("config.R")
### 1. Download ####
# Use the function to download SDGs data
do_get_sdg_api()
### 2. Data cleaning ####
# Function to clean the data downloaded
indat <- do_clean()
### 3. Tabulating ####
tab <- do_tab_country(indat, country = "Indonesia")
### 4. Visualise ####
# Generate and interactive plot with the data cleaned
do_plot()
### 5. Map ####
do_map()
```
## do_get_sdg_api
```{r, eval = FALSE}
do_get_sdg_api <- function(
output = "data_derived/sdg_14.csv"
){
# (Client URL) command line tool that enables data exchange between a device
# and a server through a terminal
curl <- paste0(
'curl -X POST --header "Content-Type: application/x-www-form-urlencoded" ',
'--header "Accept: application/octet-stream" ',
'-d "goal=14" ',
'"https://unstats.un.org/sdgapi/v1/sdg/Goal/DataCSV" -o',
output)
# Execute cURL
system(curl)
}
```
## do_clean
```{r, eval = FALSE}
do_clean <- function() {
# options(scipen = 1000)
# Load data
indat <- fread(file.path("data_derived", "sdg_14.csv"))
# mapping <- fread(file.path("data_provided", "country-to-region-mapping.csv"))
# Keep only the values that are either blank or 'A' under 'Observation Status', drop the rest
indat <- indat[`[Observation Status]` == "" | `[Observation Status]` == "A"]
# Replace '-' with '_' across all disaggregation values
cols_to_replace <- grep("\\[.*\\]",
names(indat),
value = TRUE)
indat[, (cols_to_replace) := lapply(.SD, function(x) gsub("-", "_", x)),
.SDcols = cols_to_replace]
return(indat)
}
```
## do_tab_country
```{r, eval = FALSE}
do_tab_country <- function(
indat,
country
){
# Filter the input data for the specified country
foo <- indat[GeoAreaName == country]
# Select specific columns from the filtered data
foo14 <- foo[, .(Indicator,
SeriesDescription,
TimePeriod,
Source)]
# Convert TimePeriod column to numeric for easier calculations
foo14[, NumericTimePeriod := as.numeric(TimePeriod)]
# Calculate min and max year for each SeriesDescription using TimePeriod
time_ranges <- foo14[, .(
StartYear = min(NumericTimePeriod, na.rm = TRUE),
EndYear = max(NumericTimePeriod, na.rm = TRUE)
), by = SeriesDescription]
# Create a time range string (e.g., "2000-2020" or "2000" if start and end year are the same)
time_ranges[, TimeRange := ifelse(StartYear == EndYear, as.character(StartYear), paste(StartYear, EndYear, sep = "-"))]
# Merge the new time range back to the main data.table
foo14 <- merge(foo14, time_ranges, by = "SeriesDescription", all.x = TRUE)
# Drop temporary columns that are no longer needed
foo14[, NumericTimePeriod := NULL]
foo14[, StartYear := NULL]
foo14[, EndYear := NULL]
foo14[, TimePeriod := NULL]
# Keep unique rows based on SeriesDescription
unq <- unique(foo14, by = "SeriesDescription")
# Select the final columns to include in the output
unq <- unq[, .(Indicator, SeriesDescription, TimeRange, Source)]
# Define the output file name based on the country
out_name <- paste0("data_derived/", country, "_SDG_14.csv")
# Write the data to a CSV file
fwrite(unq, out_name)
return(unq)
}
```
## do_plot
```{r, eval = FALSE}
do_plot <- function(){
# Subset the data to only include rows where the Indicator is "14.7.1"
sdg1471 <- indat[Indicator=="14.7.1"]
# Order the subsetted data by GeoAreaName in ascending order
sdg1471 <- sdg1471[order(sdg1471$GeoAreaName, decreasing = FALSE)]
# Display the unique GeoAreaNames in the subsetted and ordered data
unique(sdg1471$GeoAreaName)
# Further subset the data to only include rows where the GeoAreaName is "Indonesia"
sdg1471_ind <- sdg1471[GeoAreaName=="Indonesia"]
# Let's make a simple plot using base R
plot(
sdg1471_ind$TimePeriod,
sdg1471_ind$Value
)
# Some improvements:
# type = "l"
# col = "blue"
# lwd = 2
# main = "Sustainable Fisheries as a proportion of GDP in Indonesia"
# xlab = "Year"
# ylab = "(%)"
# Comparing Indonesia with other countries, subsetting first
sdg1471_comp <- sdg1471[GeoAreaName %in% c("Indonesia", "Malaysia", "Cook Islands")]
# Create the plot using ggplot2
ggplot(sdg1471_comp,
aes(x = TimePeriod, y = Value, color = GeoAreaName, group = GeoAreaName)) +
geom_line(size = 1.2) +
labs(title = "Sustainable Fisheries as a proportion of GDP",
x = "Year",
y = "(%)",
color = "Country") +
theme_minimal()
# Include world averages for comparison
sdg1471_comp_two <- sdg1471[GeoAreaName %in% c("Indonesia", "Malaysia", "Cook Islands", "World")]
# Create the plot using ggplot2
p <- ggplot(sdg1471_comp_two,
aes(x = TimePeriod, y = Value, color = GeoAreaName, group = GeoAreaName)) +
geom_line(size = 1.2) +
labs(title = "Sustainable Fisheries as a proportion of GDP (including World average)",
x = "Year",
y = "(%)",
color = "Country") +
theme_minimal()
return(p)
}
```
## do_map
```{r, eval = FALSE}
do_map <- function()
{
# United Nations Convention on the Law of the Sea (UNCLOS)
# Indicator 14.c.1: Number of countries making progress in ratifying,
# accepting and implementing through legal, policy and institutional frameworks,
# ocean-related instruments that implement international law, as reflected in
# the United Nations Convention on the Law of the Sea, for the conservation and
# sustainable use of the oceans and their resources
foo <- indat[SeriesCode == "ER_UNCLOS_RATACC" | SeriesCode == "ER_UNCLOS_IMPLE"]
foo1 <- foo[SeriesCode == "ER_UNCLOS_RATACC", .SD[which.max(as.numeric(TimePeriod))], by = GeoAreaName]
foo2<- foo[SeriesCode == "ER_UNCLOS_IMPLE", .SD[which.max(as.numeric(TimePeriod))], by = GeoAreaName]
# Get country polygons
world <- rnaturalearth::ne_countries(scale = "medium", returnclass = "sf")
setnames(foo1, "GeoAreaName", "name")
setnames(foo2, "GeoAreaName", "name")
foo2_names <- unique(foo2$name)
foo1_names <- unique(foo1$name)
world_names <- unique(world$name)
names_diff_foo2_world <- setdiff(foo2_names, world_names)
names_diff_foo1_world <- setdiff(foo1_names, world_names)
print("Names in foo2 not in world:")
print(names_diff_foo2_world)
print(names_diff_foo1_world)
foo2[name == "Republic of Korea", name := "South Korea"]
foo2[name == "United Kingdom of Great Britain and Northern Ireland", name := "United Kingdom"]
foo2[name == "Russian Federation", name := "Russia"]
foo2[name == "Venezuela (Bolivarian Republic of)", name := "Venezuela"]
foo1[name == "Republic of Korea", name := "South Korea"]
foo1[name == "United Kingdom of Great Britain and Northern Ireland", name := "United Kingdom"]
foo1[name == "Russian Federation", name := "Russia"]
foo1[name == "Venezuela (Bolivarian Republic of)", name := "Venezuela"]
foo2_imple <- foo2[SeriesCode == "ER_UNCLOS_IMPLE"]
foo1_rat <- foo1[SeriesCode == "ER_UNCLOS_RATACC"]
foo3 <- rbind(foo2_imple, foo1_rat)
foo3_map <- merge(world, foo3, by = "name", all.x = TRUE, fill = TRUE)
setDT(foo3_map)
# Replace NaN and NA in 'Value' with NA for uniform handling
foo3_map[, Value := fifelse(is.nan(Value) | is.na(Value), as.numeric(NA), Value)]
foo3_map[, ValueFactor := cut(Value, breaks = c(0, 50, 69, 79, 89, 100),
include.lowest = TRUE, right = TRUE,
labels = c("0-50%", "51-69%", "70-79%", "80-89%", "90-100%"))]
foo4 <- foo3_map[!is.na(foo3_map$Value)]
foo5 <- foo4[, c("name", "Value", "Indicator", "TimePeriod", "SeriesDescription"), drop = FALSE]
write.csv(foo5, "data_derived/sdg_14_unclos_map.csv", row.names = FALSE)
foo3_map <- st_as_sf(foo3_map)
equal_earth_projection <- st_crs("+proj=eqearth +datum=WGS84")
p <- ggplot(data = foo3_map) +
geom_sf(aes(geometry = geometry, fill = ValueFactor), color = "white", size = 0.2) +
scale_fill_brewer(palette = "YlGnBu", name = "", na.value = "grey") +
coord_sf(crs = equal_earth_projection, datum = NA) + # Apply Equal Earth projection
theme(
panel.background = element_rect(fill = "white"),
legend.position = "top"
)
ggsave("figures_and_tables/fig_map.png", plot = p, width = 10, height = 6, dpi = 300, units = "in")
}
```