rdb.R 17.1 KB
Newer Older
1
2
3
#' Download DBnomics data.
#'
#' \code{rdb} downloads data series from
4
#' \href{https://db.nomics.world/}{DBnomics} using shortcuts like \code{ids},
5
#' \code{dimensions}, \code{mask}, \code{query} or using an \code{api_link}.
6
7
#'
#' This function gives you access to hundreds of millions data series from
8
#' \href{https://api.db.nomics.world/}{DBnomics API} (documentation about
9
#' the API can be found \href{https://api.db.nomics.world/v22/apidocs}{here}).
10
#' The code of each series is given on the
11
12
13
14
#' \href{https://db.nomics.world/}{DBnomics website}. \cr\cr
#' In the event that only the argument \code{ids} is provided (and those in the
#' ellipsis \code{...}), the argument name can be dropped. The character string
#' vector is directly passed to \code{ids}. \cr
15
16
17
#' If only the argument \code{api_link} is provided (and those in the
#' ellipsis \code{...}), then the argument name can be dropped. The character string
#' vector is directly passed to \code{api_link}. \cr
18
19
20
#' In the same way, if only \code{provider_code}, \code{dataset_code} and
#' \code{mask} are provided then the arguments names can be dropped. The
#' last character string is automatically passed to \code{mask}.
21
#' 
22
#'
23
24
25
26
27
28
29
30
#' @param provider_code Character string (default \code{NULL}). DBnomics code
#' of the provider.
#' @param dataset_code Character string (default \code{NULL}). DBnomics code
#' of the dataset.
#' @param ids Character string (default \code{NULL}). DBnomics code of one or
#' several series.
#' @param dimensions List or character string (single quoted)  (default \code{NULL}).
#' DBnomics code of one or several dimensions in the specified provider and dataset.
31
32
#' If it is a named list, then the function \code{toJSON} (from the
#' package \pkg{jsonlite}) is applied to generate the json object.
33
34
#' @param mask Character string (default \code{NULL}). DBnomics code of one or
#' several masks in the specified provider and dataset.
35
36
#' @param query Character string (default \code{NULL}). A query to
#' filter/select series from a provider's dataset.
37
38
#' @param api_link Character string. DBnomics API link of the search. It should
#' starts with \code{http://} or \code{https://}.
39
#' @param filters List (default \code{NULL}). This argument must be a named
40
41
42
#' list for one filter because the function \code{toJSON} of the package \pkg{jsonlite}
#' is used before sending the request to the server. For multiple filters,
#' you have to provide a list of valid filters (see examples).\cr
43
44
#' A valid filter is a named list with an element \code{code} which is a character string,
#' and an element \code{parameters} which is a named list with elements \code{frequency}
45
#' and \code{method} or a NULL.
46
47
48
49
50
51
52
53
54
55
56
57
58
#' @param use_readLines Logical (default \code{FALSE}). If \code{TRUE}, then
#' the data are requested and read with the base function \code{readLines} i.e.
#' through the default R internet connection. This can be used to get round the
#' error \code{Could not resolve host: api.db.nomics.world}.
#' @param curl_config Named list (default \code{NULL}). If not
#' \code{NULL}, it is used to configure a proxy connection. This
#' configuration is passed to the function \code{curl_fetch_memory} of the package
#' \pkg{curl}. A temporary \code{curl_handle} object is created internally
#' with arguments equal to the provided list in \code{curl_config}.\cr
#' For \code{curl_fetch_memory} arguments see \code{\link[curl]{curl_fetch}}.
#' For available curl options see \code{\link[curl]{curl_options}},
#' \code{names(curl_options())} and
#' \href{https://curl.haxx.se/libcurl/c/curl_easy_setopt.html}{libcurl}.
59
#' @param verbose Logical (default \code{FALSE}). Show warnings of the function.
60
#' @param ... Arguments to be passed to the internal function \code{.rdb}.
61
#' @return A \code{data.table}.
62
#' @examples
63
#' \dontrun{
64
#' ## By ids
65
#' # Fetch one series from dataset 'Unemployment rate' (ZUTN) of AMECO provider:
66
#' df1 <- rdb(ids = "AMECO/ZUTN/EA19.1.0.0.0.ZUTN")
67
#' # or when no argument names are given (provider_code -> ids)
68
#' df1 <- rdb("AMECO/ZUTN/EA19.1.0.0.0.ZUTN")
69
#'
70
#' # Fetch two series from dataset 'Unemployment rate' (ZUTN) of AMECO provider:
71
#' df2 <- rdb(ids = c("AMECO/ZUTN/EA19.1.0.0.0.ZUTN", "AMECO/ZUTN/DNK.1.0.0.0.ZUTN"))
72
#'
73
74
#' # Fetch two series from different datasets of different providers:
#' df3 <- rdb(ids = c("AMECO/ZUTN/EA19.1.0.0.0.ZUTN", "IMF/BOP/A.FR.BCA_BP6_EUR"))
75
76
#'
#'
77
#' ## By dimensions
78
#' # Fetch one value of one dimension from dataset 'Unemployment rate' (ZUTN) of AMECO provider:
79
#' df1 <- rdb("AMECO", "ZUTN", dimensions = list(geo = "ea12"))
80
#' # or
81
#' df1 <- rdb("AMECO", "ZUTN", dimensions = '{"geo":["ea12"]}')
82
#'
83
#' # Fetch two values of one dimension from dataset 'Unemployment rate' (ZUTN) of AMECO provider:
84
#' df2 <- rdb("AMECO", "ZUTN", dimensions = list(geo = c("ea12", "dnk")))
85
#' # or
86
#' df2 <- rdb("AMECO", "ZUTN", dimensions = '{"geo":["ea12","dnk"]}')
87
#'
88
#' # Fetch several values of several dimensions from dataset 'Doing business' (DB) of World Bank:
89
90
91
92
#' dim <- list(
#'   country = c("DZ", "PE"),
#'   indicator = c("ENF.CONT.COEN.COST.ZS", "IC.REG.COST.PC.FE.ZS")
#' )
93
#' df3 <- rdb("WB", "DB", dimensions = dim)
94
95
#' # or
#' dim <- paste0(
96
97
#'   '{"country":["DZ","PE"],',
#'   '"indicator":["ENF.CONT.COEN.COST.ZS","IC.REG.COST.PC.FE.ZS"]}'
98
#' )
99
#' df3 <- rdb("WB", "DB", dimensions = dim)
100
101
#'
#'
102
#' ## By mask
103
104
#' # Fetch one series from dataset 'Balance of Payments' (BOP) of IMF:
#' df1 <- rdb("IMF", "BOP", mask = "A.FR.BCA_BP6_EUR")
105
#' # or when no argument names are given except provider_code and dataset_code (ids -> mask)
106
#' df1 <- rdb("IMF", "BOP", "A.FR.BCA_BP6_EUR")
107
#'
108
109
#' # Fetch two series from dataset 'Balance of Payments' (BOP) of IMF:
#' df2 <- rdb("IMF", "BOP", mask = "A.FR+ES.BCA_BP6_EUR")
110
#'
111
112
#' # Fetch all series along one dimension from dataset 'Balance of Payments' (BOP) of IMF:
#' df3 <- rdb("IMF", "BOP", mask = "A..BCA_BP6_EUR")
113
#'
114
115
#' # Fetch series along multiple dimensions from dataset 'Balance of Payments' (BOP) of IMF:
#' df4 <- rdb("IMF", "BOP", mask = "A.FR.BCA_BP6_EUR+IA_BP6_EUR")
116
117
#'
#'
118
#' ## By query
119
120
121
122
#' # Fetch one series from dataset 'WEO by countries (2019-10 release)' (WEO:2019-10) from IMF :
#' df1 <- rdb("IMF", "WEO:2019-10", query = "France current account balance percent")
#' # Fetch series from dataset 'WEO by countries (2019-10 release)' (WEO:2019-10) from IMF :
#' df2 <- rdb("IMF", "WEO:2019-10", query = "current account balance percent")
123
124
#' 
#' 
125
#' ## By api_link
126
127
#' # Fetch two series from different datasets of different providers :
#' df1 <- rdb(
128
#'   api_link = paste0(
129
130
131
132
133
134
135
#'     "https://api.db.nomics.world/v22/",
#'     "series?observations=1&series_ids=AMECO/ZUTN/EA19.1.0.0.0.ZUTN,IMF/CPI/A.AT.PCPIT_IX"
#'   )
#' )
#' 
#' # Fetch one series from the dataset 'Doing Business' of WB provider :
#' df2 <- rdb(
136
#'   api_link = paste0(
137
138
139
140
141
#'     "https://api.db.nomics.world/v22/series/WB/DB?dimensions=%7B%22",
#'     "indicator%22%3A%5B%22IC.REG.PROC.FE.NO%22%5D%7D&q=Doing%20Business",
#'     "&observations=1&format=json&align_periods=1&offset=0&facets=0"
#'   )
#' )
142
143
144
145
146
147
148
#' # or when no argument names are given (provider_code -> api_link)
#' df1 <- rdb(
#'   paste0(
#'     "https://api.db.nomics.world/v22/",
#'     "series?observations=1&series_ids=AMECO/ZUTN/EA19.1.0.0.0.ZUTN,IMF/CPI/A.AT.PCPIT_IX"
#'   )
#' )
149
150
#' 
#' 
151
#' ## Use a specific proxy to fetch the data
152
#' # Fetch one series from dataset 'Unemployment rate' (ZUTN) of AMECO provider :
153
154
155
156
157
158
159
#' h <- list(
#'   proxy = "<proxy>",
#'   proxyport = <port>,
#'   proxyusername = "<username>",
#'   proxypassword = "<password>"
#' )
#' options(rdbnomics.curl_config = h)
160
#' df1 <- rdb(ids = "AMECO/ZUTN/EA19.1.0.0.0.ZUTN")
161
#' # or to use once
162
#' options(rdbnomics.curl_config = NULL)
163
#' df1 <- rdb(ids = "AMECO/ZUTN/EA19.1.0.0.0.ZUTN", curl_config = h)
164
165
#'
#'
166
#' ## Use R default connection to avoid a proxy failure (in some cases)
167
#' # Fetch one series from dataset 'Unemployment rate' (ZUTN) of AMECO provider :
168
#' options(rdbnomics.use_readLines = TRUE)
169
#' df1 <- rdb(ids = "AMECO/ZUTN/EA19.1.0.0.0.ZUTN")
170
#' # or to use once
171
#' df1 <- rdb(ids = "AMECO/ZUTN/EA19.1.0.0.0.ZUTN", use_readLines = TRUE)
172
173
174
175
176
#' 
#' 
#' ## Apply filter(s) to the series
#' # One filter
#' df1 <- rdb(
177
#'   ids = c("IMF/WEO:2019-10/ABW.BCA.us_dollars", "IMF/WEO:2019-10/ABW.BCA_NGDPD.pcent_gdp"),
178
179
180
181
182
183
184
185
#'   filters = list(
#'     code = "interpolate",
#'     parameters = list(frequency = "daily", method = "spline")
#'   )
#' )
#' 
#' # Two filters
#' df1 <- rdb(
186
#'   ids = c("IMF/WEO:2019-10/ABW.BCA.us_dollars", "IMF/WEO:2019-10/ABW.BCA_NGDPD.pcent_gdp"),
187
188
189
190
191
192
193
194
195
196
197
#'   filters = list(
#'     list(
#'       code = "interpolate",
#'       parameters = list(frequency = "quarterly", method = "spline")
#'     ),
#'     list(
#'       code = "aggregate",
#'       parameters = list(frequency = "annual", method = "average")
#'     )
#'   )
#' )
198
#' }
199
#' @author Sebastien Galais
200
#' @export
201
rdb <- function(
202
  provider_code = NULL, dataset_code = NULL,
203
  ids = NULL, dimensions = NULL, mask = NULL, query = NULL, api_link = NULL,
204
  filters = getOption("rdbnomics.filters"),
205
206
  use_readLines = getOption("rdbnomics.use_readLines"),
  curl_config = getOption("rdbnomics.curl_config"),
207
208
209
210
  verbose = getOption("rdbnomics.verbose_warning"),
  ...
) {
  # Checking 'verbose'
211
212
213
214
215
216
217
218
219
220
221
  check_argument(verbose, "logical")

  # Setting API url
  api_base_url <- getOption("rdbnomics.api_base_url")
  check_argument(api_base_url, "character")

  # Setting API version
  api_version <- getOption("rdbnomics.api_version")
  check_argument(api_version, c("numeric", "integer"))
  authorized_version(api_version)

222
223
224
225
226
  # Setting API metadata
  metadata <- getOption("rdbnomics.metadata")
  check_argument(metadata, "logical")

  # Building API base url
227
  api_base_url <- paste0(api_base_url, "/v", api_version, "/series")
228
229
230
231

  # Checking arguments
  provider_code_null <- is.null(provider_code)
  provider_code_not_null <- !provider_code_null
232

233
234
235
236
237
  dataset_code_null <- is.null(dataset_code)
  dataset_code_not_null <- !dataset_code_null

  dimensions_null <- is.null(dimensions)
  dimensions_not_null <- !dimensions_null
238

239
240
  mask_null <- is.null(mask)
  mask_not_null <- !mask_null
241

242
243
244
  ids_null <- is.null(ids)
  ids_not_null <- !ids_null

245
246
247
  query_null <- is.null(query)
  query_not_null <- !query_null

248
249
  api_link_null <- is.null(api_link)
  api_link_not_null <- !api_link_null
250

251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
  # provider_code is considered as api_link in some cases
  if (
    provider_code_not_null & dataset_code_null & dimensions_null & mask_null &
    ids_null & query_null & api_link_null & getOption("rdbnomics.rdb_no_arg")
  ) {
    is_http <- grepl("^http(s)*://", tolower(provider_code))
    if (sum(is_http, na.rm = TRUE) > 0) {
      fcall <- sys.call()
      modif_arg <- call_ok(fcall)

      if (modif_arg) {
        api_link <- provider_code
        provider_code <- NULL

        provider_code_null <- TRUE
        provider_code_not_null <- !provider_code_null

        api_link_null <- FALSE
        api_link_not_null <- !api_link_null
      }
    }
  }

274
275
276
  # By api_link i.e. .rdb(api_link = api_link)
  if (api_link_not_null) {
    check_argument(api_link, "character", not_null = FALSE)
277
278
279
    
    if (api_version == 22) {
      return(
280
281
        .rdb(
          api_link = api_link, filters = filters,
282
283
284
285
286
287
288
289
290
291
292
          use_readLines = use_readLines, curl_config = curl_config, ...
        )
      )
    } else {
      stop(
        paste0("Don't know what to do for API version ", api_version, "."),
        call. = FALSE
      )
    }
  }

293
294
295
  # provider_code is considered as ids in some cases
  if (
    provider_code_not_null & dataset_code_null & dimensions_null & mask_null &
296
    ids_null & query_null & api_link_null & getOption("rdbnomics.rdb_no_arg")
297
298
  ) {
    fcall <- sys.call()
299
    modif_arg <- call_ok(fcall)
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315

    if (modif_arg) {
      ids <- provider_code
      provider_code <- NULL

      provider_code_null <- TRUE
      provider_code_not_null <- !provider_code_null

      ids_null <- FALSE
      ids_not_null <- !ids_null
    }
  }

  # ids is considered as mask in some cases
  if (
    provider_code_not_null & dataset_code_not_null & dimensions_null &
316
317
    mask_null & ids_not_null & query_null & api_link_null &
    getOption("rdbnomics.rdb_no_arg")
318
319
  ) {
    fcall <- sys.call()
320
    modif_arg <- call_ok(fcall)
321
322
323
324

    if (modif_arg) {
      mask <- ids
      ids <- NULL
325

326
327
      mask_null <- FALSE
      mask_not_null <- !mask_null
328

329
330
331
332
333
      ids_null <- TRUE
      ids_not_null <- !ids_null
    }
  }

334
335
336
337
338
339
340
  # By dimensions
  if (dimensions_not_null) {
    if (provider_code_null | dataset_code_null) {
      stop(
        paste0(
          "When you filter with 'dimensions', you must specifiy ",
          "'provider_code' and 'dataset_code' as arguments of the function."
341
342
        ),
        call. = FALSE
343
      )
344
    }
345

346
347
    dimensions <- to_json_if_list(dimensions)
    check_argument(dimensions, c("character", "json"), not_null = FALSE)
348
349
    check_argument(provider_code, "character", not_null = FALSE)
    check_argument(dataset_code, "character", not_null = FALSE)
350

351
    if (api_version == 21) {
352
      link <- paste0(
353
354
        api_base_url, "?provider_code=", provider_code,
        "&dataset_code=", dataset_code, "&dimensions=", dimensions
355
356
      )
    } else if (api_version == 22) {
357
      link <- paste0(
358
        api_base_url, "/", provider_code, "/", dataset_code,
359
360
        ifelse(metadata, "?", paste0("?metadata=", as.numeric(metadata), "&")),
        "observations=1&dimensions=", dimensions
361
362
      )
    } else {
363
364
365
366
      stop(
        paste0("Don't know what to do for API version ", api_version, "."),
        call. = FALSE
      )
367
    }
368

369
    return(
370
      .rdb(
371
372
373
374
        api_link = link, filters = filters,
        use_readLines = use_readLines, curl_config = curl_config, ...
      )
    )
375
376
377
378
379
380
381
382
383
  }

  # By mask
  if (mask_not_null) {
    if (provider_code_null | dataset_code_null) {
      stop(
        paste0(
          "When you filter with 'mask', you must specifiy 'provider_code' ",
          "and 'dataset_code' as arguments of the function."
384
385
        ),
        call. = FALSE
386
387
388
      )
    }

389
390
391
    check_argument(mask, "character", not_null = FALSE)
    check_argument(provider_code, "character", not_null = FALSE)
    check_argument(dataset_code, "character", not_null = FALSE)
392

393
    if (api_version == 21) {
394
      link <- paste0(
395
396
        api_base_url, "?provider_code=", provider_code,
        "&dataset_code=", dataset_code, "&series_code_mask=", mask
397
398
      )
    } else if (api_version == 22) {
399
      link <- paste0(
400
        api_base_url, "/", provider_code, "/", dataset_code,
401
402
403
        "/", mask,
        ifelse(metadata, "?", paste0("?metadata=", as.numeric(metadata), "&")),
        "observations=1"
404
405
      )
    } else {
406
407
408
409
      stop(
        paste0("Don't know what to do for API version ", api_version, "."),
        call. = FALSE
      )
410
411
    }

412
    return(
413
      .rdb(
414
415
416
417
        api_link = link, filters = filters,
        use_readLines = use_readLines, curl_config = curl_config, ...
      )
    )
418
419
420
421
422
423
424
425
426
427
428
429
  }

  # By ids
  if (ids_not_null) {
    if (provider_code_not_null | dataset_code_not_null) {
      if (verbose) {
        warning(
          paste0(
            "When you filter with 'ids', ",
            "'provider_code' and 'dataset_code' are not considered."
          )
        )
430
431
432
      }
    }

433
    if (!is.character(ids)) {
434
      stop("'ids' must be of class 'character'.", call. = FALSE)
435
436
    }
    if (length(ids) <= 0) {
437
      stop("'ids' is empty.", call. = FALSE)
438
    }
439

440
    if (api_version == 21) {
441
      link <- paste0(
442
        api_base_url, "?series_ids=", paste(ids, collapse = ",")
443
      )
444
    } else if (api_version == 22) {
445
      link <- paste0(
446
447
448
        api_base_url,
        ifelse(metadata, "?", paste0("?metadata=", as.numeric(metadata), "&")),
        "observations=1&series_ids=",
449
        paste(ids, collapse = ",")
450
451
      )
    } else {
452
453
454
455
      stop(
        paste0("Don't know what to do for API version ", api_version, "."),
        call. = FALSE
      )
456
457
    }

458
    return(
459
      .rdb(
460
461
462
463
        api_link = link, filters = filters,
        use_readLines = use_readLines, curl_config = curl_config, ...
      )
    )
464
465
  }

466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
  # By query
  if (query_not_null) {
    if (provider_code_null | dataset_code_null) {
      stop(
        paste0(
          "When you filter with a 'query', you must specifiy 'provider_code' ",
          "and 'dataset_code' as arguments of the function."
        ),
        call. = FALSE
      )
    }

    check_argument(query, "character", not_null = FALSE)

    if (verbose) {
      if (query == "") {
        warning(
          paste0(
            "Your 'query' is empty, the entire dataset ",
            provider_code, "/", dataset_code,
            " will be downloaded. It can be long !"
          )
        )
      }
    }

    if (api_version == 22) {
      link <- paste0(
        api_base_url, "/", provider_code, "/", dataset_code,
        "?q=", utils::URLencode(query),
        ifelse(metadata, "&", paste0("&metadata=", as.numeric(metadata), "&")),
        "observations=1"
      )
    } else {
      stop(
        paste0("Don't know what to do for API version ", api_version, "."),
        call. = FALSE
      )
    }

506
    return(
507
      .rdb(
508
509
510
511
        api_link = link, filters = filters,
        use_readLines = use_readLines, curl_config = curl_config, ...
      )
    )
512
513
  }

514
  stop(
515
516
    "Please provide correct 'provider_code', 'dataset_code', 'dimensions', ",
    "'mask', 'ids', 'query', 'api_link' or 'filters'.",
517
518
    call. = FALSE
  )
519
}