-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.R
204 lines (189 loc) · 8.01 KB
/
index.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
# Programmatically require libraries
list.of.packages <- c("data.table", "jsonlite", "httr", "XML", "tidyr", "reshape2", "stringr", "here")
new.packages <- list.of.packages[!(list.of.packages %in% installed.packages()[,"Package"])]
if(length(new.packages)) install.packages(new.packages)
lapply(list.of.packages, require, character.only=T)
# Set working directory
wd = here()
setwd(wd)
rm(list.of.packages, new.packages, wd)
# Set version to 2.03 and language to English
VERSION = "2.03"
LANGUAGE = "en"
STANDARD = "activity"
# A function to convert xpath names to Datastore field names
convertNameToCanonical = function(xpath) {
retval = xpath
retval = gsub("//iati-activities/", "", retval)
retval = gsub("//iati-activity/", "", retval)
retval = gsub("//iati-organisations/", "", retval)
retval = gsub("//iati-organisation/", "", retval)
retval = gsub("//@", "", retval)
retval = gsub("/text()", "", retval, fixed=T)
if(startsWith(retval, "@")){
retval = substr(retval, 2, nchar(retval))
}
retval = gsub("/@", "@", retval)
retval = gsub("-", "_", retval)
retval = gsub(":", "_", retval)
retval = gsub("/", "@", retval)
retval = gsub("@", "_", retval)
return(retval)
}
convertNameToCanonical = Vectorize(convertNameToCanonical)
# Pull in codelist mapping in XML
mapping_list = list()
mapping_url = paste0(
"https://raw.githubusercontent.com/IATI/IATI-Codelists/version-",
VERSION,
"/mapping.xml"
)
mapping_content = content(GET(mapping_url))
mapping_xml = xmlParse(mapping_content)
mappings = getNodeSet(mapping_xml,"/mappings/mapping")
for(i in 1:length(mappings)){
mapping = mappings[[i]]
path = xmlValue(getNodeSet(mapping, "./path")[[1]])
codelist = xmlAttrs(getNodeSet(mapping, "./codelist")[[1]])[["ref"]]
condition_node = getNodeSet(mapping, "./condition")
if(length(condition_node) == 0){
condition = NA
}else{
condition = xmlValue(condition_node[[1]])
}
mapping_list[[i]] = data.frame(path, codelist, condition)
}
mapping_df = rbindlist(mapping_list)
mapping_df$datastore_name = convertNameToCanonical(mapping_df$path)
# Special case
mapping_df$datastore_name[which(mapping_df$path=="//iati-activities/@version")] = "dataset_version"
# Find unique codelists and download
cl_list = list()
unique_codelists = unique(mapping_df$codelist)
cl_count = 1
pb = txtProgressBar(max=length(unique_codelists), style=3)
for(codelist in unique_codelists){
setTxtProgressBar(pb, cl_count)
codelist_url = paste0(
"https://cdn.iatistandard.org/prod-iati-website/reference_downloads/",
gsub(".","",VERSION,fixed=T),
"/codelists/downloads/clv3/json/",
LANGUAGE,
"/",
codelist,
".json"
)
tmp_codelist_df = fromJSON(codelist_url)$data
tmp_codelist_df$codelist = codelist
cl_list[[cl_count]] = tmp_codelist_df
cl_count = cl_count + 1
}
close(pb)
codelist_df = rbindlist(cl_list, fill=T)
codelist_df$name[which(is.na(codelist_df$name))] = codelist_df$code[which(is.na(codelist_df$name))]
# Split out conditional and unconditional mappings
unconditional_mappings = subset(mapping_df, is.na(condition))
conditional_mappings = subset(mapping_df, !is.na(condition))
conditional_mappings$path = as.character(conditional_mappings$path)
conditional_mappings$condition = as.character(conditional_mappings$condition)
# A function to remove attributes from xpath
stripAttributePath = function(xpath){
split_xpath = strsplit(xpath, split="/")[[1]]
if(startsWith(split_xpath[length(split_xpath)], "@")){
split_xpath = split_xpath[c(1:(length(split_xpath)-1))]
}
return(paste(split_xpath, collapse="/"))
}
stripAttributePath = Vectorize(stripAttributePath)
# A function to fetch parent xpaths
parentPath = function(xpath, generations=1){
split_xpath = strsplit(xpath, split="/")[[1]]
split_xpath = split_xpath[c(1:(length(split_xpath)-generations))]
return(paste(split_xpath, collapse="/"))
}
parentPath = Vectorize(parentPath)
conditional_mappings$condition_path = stripAttributePath(conditional_mappings$path)
conditional_mappings$condition_path[which(startsWith(conditional_mappings$condition, ".."))] = parentPath(
conditional_mappings$condition_path[which(startsWith(conditional_mappings$condition, ".."))]
)
conditional_mappings = separate(conditional_mappings, col="condition", sep=" or ", into=c("condition_1", "condition_2"))
cm_melt = melt(conditional_mappings, measure.vars=c("condition_1", "condition_2"), value.name = "condition")
cm_melt$variable = NULL
cm_melt = subset(cm_melt, !is.na(condition))
cm_melt$condition_attribute = str_extract(cm_melt$condition, regex("@(\\w)+"))
cm_melt$condition_value = gsub("(=|\\s|')","",str_extract(cm_melt$condition, regex("= '.+'")))
cm_melt$condition = NULL
cm_melt$condition_path = paste(cm_melt$condition_path, cm_melt$condition_attribute, sep="/")
cm_melt$condition_attribute = NULL
cm_melt$condition_datastore_name = convertNameToCanonical(cm_melt$condition_path)
cm_melt = cm_melt[,c("codelist", "path", "datastore_name", "condition_datastore_name", "condition_value")]
unconditional_mappings = unconditional_mappings[,c("codelist", "path","datastore_name")]
joined_mappings = rbindlist(list(unconditional_mappings, cm_melt), fill=T)
joined_mappings$path = as.character(joined_mappings$path)
if(STANDARD=="activity"){
joined_mappings = subset(
joined_mappings,
startsWith(path, "//iati-activity") | startsWith(path, "//iati-activities") | startsWith(path, "//@xml:lang")
)
}else{
joined_mappings = subset(
joined_mappings,
startsWith(path, "//iati-organisation") | startsWith(path, "//iati-organisations") | startsWith(path, "//@xml:lang")
)
}
# Load sample data and recode
sample_data = fromJSON("data/sample.json", simplifyDataFrame = F)$response$docs
for(i in 1:length(sample_data)){
row = sample_data[[i]]
row_length = length(row)
for(j in 1:row_length){
value_codes = row[[j]]
field_name = names(row)[j]
new_field_name = paste0(field_name, "_recode")
if(field_name %in% joined_mappings$datastore_name){
jm_sub = subset(joined_mappings, datastore_name==field_name)
if(nrow(jm_sub)==1 && is.na(jm_sub$condition_datastore_name)){
# Unconditional
cl_sub = subset(codelist_df, codelist==jm_sub$codelist, select=c("code", "name"))
cl_sub = rbind(cl_sub, data.frame(code="", name=""))
value_names = merge(data.frame(code=value_codes), cl_sub, by="code")$name
sample_data[[i]][[new_field_name]] = as.character(value_names)
}else{
# Conditional
conditional_datastore_name = unique(jm_sub$condition_datastore_name)
cond_compare_values = row[[conditional_datastore_name]]
if(length(cond_compare_values) == 0){
cond_compare_values = rep(NA, length(sample_data[[i]][[j]]))
}
for(k in 1:length(cond_compare_values)){
if(is.na(cond_compare_values[k]) || cond_compare_values[k]==""){
jm_sub = subset(jm_sub, is.na(condition_value))
}else{
jm_sub = subset(jm_sub, condition_value==cond_compare_values[k])
}
if(nrow(jm_sub) == 0){
next; # No codelist for this dependent value
}
cl_sub = subset(codelist_df, codelist==jm_sub$codelist, select=c("code", "name"))
cl_sub = rbind(cl_sub, data.frame(code="", name=""))
value_code = sample_data[[i]][[j]][[k]]
value_name = merge(data.frame(code=value_code), cl_sub, by="code")$name
if(length(value_name) > 0){
if(!new_field_name %in% names(sample_data[[i]])){
sample_data[[i]][[new_field_name]] = sample_data[[i]][[j]]
}
sample_data[[i]][[new_field_name]][[k]] = as.character(value_name)
}else{
warning(paste(value_code, "is not in codelist", jm_sub$codelist))
}
}
}
}
}
}
stopifnot(
(sample_data[[1]][["country_budget_items_budget_item_code"]] == "5.1.1"),
(sample_data[[1]][["country_budget_items_budget_item_code_recode"]] == "Health - policy, planning and administration"),
(sample_data[[1]][["dataset_version"]] == "2.03"),
(sample_data[[1]][["dataset_version_recode"]] == "2.03")
)