This repository has been archived by the owner on Oct 24, 2023. It is now read-only.
forked from Edouard-Legoupil/koboloadeR
/
kobo_ddi.R
289 lines (263 loc) · 10.4 KB
/
kobo_ddi.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
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
#' @name kobo_ddi
#' @rdname kobo_ddi
#' @title DDI generation
#'
#' @description This function creates a DDI version 2.5, XML file structure for microdata library
#' @param form The full filename of the form to be accessed (xls or xlsx file).
#' It is assumed that the form is stored in the data folder.
#'
#' @param app The place where the function has been executed, the default is the console and the second option is the shiny app
#'
#' @return DDI version 2.5, XML file structure will saved under out/ddi
#'
#' @author Maher Daoud
#'
#'
#' @examples
#' \dontrun{
#' kobo_ddi("myform.xlsx")
#' }
#'
#' @export kobo_ddi
#'
kobo_ddi <- function(form = "form.xlsx", app="console") {
tryCatch({
if (app == "shiny") {
progress <- shiny::Progress$new()
progress$set(message = "Generating DDI XML file in progress...", value = 0)
on.exit(progress$close())
updateProgress <- function(value = NULL, detail = NULL) {
if (is.null(value)) {
value <- progress$getValue()
value <- value + (progress$getMax() - value) / 5
}
progress$set(value = value, detail = detail)
}
updateProgress()
}
mainDir <- kobo_getMainDirectory()
form_tmp <- paste(mainDir, "data", form, sep = "/", collapse = "/")
dico <- readr::read_csv(paste0(mainDir,"/data/dico_",form,".csv"))
survey <- tryCatch({
as.data.frame(read_excel(form_tmp, sheet = "survey"),
stringsAsFactors = FALSE) #read survey sheet from the form
},
error = function(err) {
data.frame( #if it doesn't exist, we need to create empty dataframe with those fields
type = character(),
name = character(),
label = character(),
"labelReport" = character(),
variable = character(),
disaggregation = character(),
chapter = character(),
structuralequation.risk = character(),
structuralequation.coping = character(),
structuralequation.resilience = character(),
anonymise = character(),
correlate = character(),
clean = character(),
cluster = character(),
predict = character(),
mappoint = character(),
mappoly = character(),
stringsAsFactors = FALSE,
check.names = F
)
})
if (app == "shiny") {
updateProgress()
}
survey <- survey[!is.na(survey$chapter),]
survey <- survey[c("type","name","labelReport","variable")]
survey <- survey[!startsWith(tolower(survey$type), "select_multiple"),]
survey <- survey[tolower(survey$type) != "begin_repeat" & tolower(survey$type) != "begin repeat" & tolower(survey$type) != "begin-repeat" &
tolower(survey$type) != "end_repeat" & tolower(survey$type) != "end repeat" & tolower(survey$type) != "end-repeat"
,]
survey$listname <- sapply(survey[,"type"], function(x) {
strsplit(x," ")[[1]][2]
}, simplify = TRUE, USE.NAMES = FALSE)
if (app == "shiny") {
updateProgress()
}
indicator <- tryCatch({
as.data.frame(read_excel(form_tmp, sheet = "indicator"),stringsAsFactors = FALSE)
},
error = function(err) {
data.frame(
type = character(),
fullname = character(),
label = character(),
chapter = character(),
disaggregation = character(),
correlate = character(),
sensitive = character(),
anonymise = character(),
cluster = character(),
predict = character(),
variable = character(),
mappoint = character(),
mappoly = character(),
structuralequation = character(),
frame = character(),
listname = character(),
calculation = character(),
stringsAsFactors = FALSE
)
})
if (app == "shiny") {
updateProgress()
}
indicator <- indicator[c("type","fullname","label","variable","listname")]
names(indicator) <- c("type","name","labelReport","variable","listname")
choices <- tryCatch({
as.data.frame(read_excel(form_tmp, sheet = "choices"),
stringsAsFactors = FALSE) #read survey sheet from the form
},
error = function(err) {
data.frame( #if it doesn't exist, we need to create empty dataframe with those fields
list_name = character(),
name = character(),
label = character(),
labelReport = character(),
order = character(),
stringsAsFactors = FALSE,
check.names = F
)
})
if ( app == "shiny" ) {
updateProgress()
}
dicoSelectMultiple <- dico[dico$type == "select_multiple",c("type","fullname","label","variable","listname")]
names(dicoSelectMultiple) <- c("type","name","labelReport","variable","listname")
var_ind <- rbind(survey, indicator ,dicoSelectMultiple)
dataDscr <- list()
dataDscrNames <- c()
for (i in 1:nrow(var_ind)) {
if (startsWith(tolower(var_ind[i,"type"]), "select_one")) {
ln <- var_ind[i,"listname"]
val <- choices[choices$list_name == ln, c("name", "label")]
val <- val[!is.na(val$name),]
namesVal <- c()
labelsVal <- c()
for (j in 1:nrow(val)) {
namesVal <- c(namesVal,val[j,"name"])
labelsVal <- c(labelsVal,val[j,"label"])
}
names(namesVal) <- labelsVal
dataDscr[[var_ind[i,"name"]]] = list(
label = var_ind[i,"labelReport"],
type = "char",
measurement = var_ind[i,"variable"],
values = namesVal
)
dataDscrNames <- c(dataDscrNames, var_ind[i,"name"])
} else if (startsWith(tolower(var_ind[i,"type"]), "select_multiple")) {
ln <- var_ind[i,"listname"]
val <- choices[choices$list_name == ln, c("name", "label")]
val <- val[!is.na(val$name),]
namesVal <- c()
labelsVal <- c()
for (j in 1:nrow(val)) {
namesVal <- c(namesVal,val[j,"name"])
labelsVal <- c(labelsVal,val[j,"label"])
}
names(namesVal) <- labelsVal
dataDscr[[var_ind[i,"name"]]] = list(
label = var_ind[i,"labelReport"],
type = "char",
measurement = var_ind[i,"variable"],
values = namesVal
)
dataDscrNames <- c(dataDscrNames, var_ind[i,"name"])
}else{
if (var_ind[i,"type"] %in% c("integer","numeric")) {
tp <- "num"
} else {
tp <- "char"
}
dataDscr[[var_ind[i,"name"]]] = list(
label = var_ind[i,"labelReport"],
type = tp,
measurement = var_ind[i,"variable"]
)
dataDscrNames <- c(dataDscrNames, var_ind[i,"name"])
}
}
if (app == "shiny") {
updateProgress()
}
####################### MAIN DATAFRAME #####################
configInfo <- kobo_get_config(form)
configInfo <- configInfo[startsWith(tolower(configInfo$name), "instanceid"),]
configInfo <- configInfo[!is.na(configInfo$name),]
levelsOfDF <- kobo_get_dataframes_levels(form)
levelsOfDF <- levelsOfDF[levelsOfDF$name != "MainDataFrame",]
levelsOfDF[levelsOfDF$parent == "MainDataFrame","parent"] <- "household"
levelsOfDF$flag <- T
levelsOfDF <- levelsOfDF[order(desc(levelsOfDF$level), desc(levelsOfDF$parent)),]
count <- 0
for (dbr in levelsOfDF$name) {
if (levelsOfDF[levelsOfDF$name == dbr, "flag"] == F) {
next
}
count <- count + 1
dataFrame <- readr::read_csv(paste(mainDir,"/data/",dbr,"-edited.csv",sep = ""),stringsAsFactors = F)
dataFrame <- kobo_split_multiple(dataFrame, dico)
#dataFrame <- kobo_clean(dataFrame, dico)
dataFrame <- kobo_label(dataFrame, dico)
child <- levelsOfDF[levelsOfDF$name == dbr, "name"]
parent <- levelsOfDF[levelsOfDF$name == dbr, "parent"]
while (T) {
cat("Join child dataframe", child, "with the parent", parent)
instanceIDChild <- configInfo[tolower(configInfo$name) == tolower(paste0("instanceid_",child,"_",
ifelse(parent == "household","MainDataFrame",parent))), "value"]
instanceIDParent <- configInfo[tolower(configInfo$name) == tolower(paste0("instanceid_",
ifelse(parent == "household","MainDataFrame",parent),"_",child)), "value"]
parentDf <- readr::read_csv(paste(mainDir,"/data/",parent,".csv",sep = ""),stringsAsFactors = F)
unColChild <- dataFrame[,instanceIDChild]
dataFrame <- dataFrame[,colnames(dataFrame) != instanceIDChild]
unCN <- colnames(dataFrame)[!colnames(dataFrame) %in% colnames(parentDf)]
unCN <- c(instanceIDChild, unCN)
dataFrame[instanceIDChild] <- unColChild
dataFrame <- dataFrame[ unCN ]
dataFrame <- plyr::join(x = parentDf, y = dataFrame, by = setNames(instanceIDParent, instanceIDChild), type = "left")
if (parent == "household") {
break
}else{
child <- levelsOfDF[levelsOfDF$name == parent, "name"]
parent <- levelsOfDF[levelsOfDF$name == parent, "parent"]
levelsOfDF[levelsOfDF$name == parent, "flag"] <- F
}
}
readr::write_csv(dataFrame,paste(mainDir,"/data/group",count,".csv",sep = ""))
}
allframes <- readr::read_csv(paste(mainDir,"/data/group",count,".csv",sep = ""), stringsAsFactors = F)
count <- count - 1
while (count) {
temp <- readr::read_csv(paste(mainDir,"/data/group",count,".csv",sep = ""), stringsAsFactors = F)
unColChild <- temp[,"responseID"]
temp <- temp[,colnames(temp) != instanceIDChild]
unCN <- colnames(temp)[!colnames(temp) %in% colnames(allframes)]
unCN <- c("responseID", unCN)
temp[instanceIDChild] <- unColChild
temp <- temp[ unCN ]
allframes <- plyr::join(x = allframes, y = temp, by = "responseID", type = "full")
count <- count - 1
}
############################################################
dataDscrNames <- dataDscrNames[dataDscrNames %in% colnames(allframes)]
dataDscr <- dataDscr[dataDscrNames]
allframes <- allframes[dataDscrNames]
codeBook <- list(
fileDscr = list(
datafile = allframes
),
dataDscr = dataDscr
)
DDIwR::exportDDI(codeBook, file = paste0(mainDir,paste0("/out/ddi/ddi_output-",Sys.Date(),".xml")))
}, error = function(err) {
print("kobo_ddi_ERROR")
return(structure(err, class = "try-error"))
})
}