-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathutil_functions.R
1541 lines (1319 loc) · 41.6 KB
/
util_functions.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
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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
### ctrdata package
### utility functions
#### variable definitions ####
# prototype return structure
emptyReturn <- list(n = 0L, success = NULL, failed = NULL)
#
# EUCTR definitions
countriesEUCTR <- c(
"AT", "BE", "BG", "HR", "CY", "CZ", "DK", "EE", "FI", "FR",
"DE", "GR", "HU", "IE", "IT", "LV", "LT", "LU", "MT", "NL",
"PL", "PT", "RO", "SK", "SE", "SI", "ES", "GB", "IS", "LI",
"NO", "3RD")
#
# regexpr
# - queryterm and urls
regQueryterm <- "[^-.a-zA-Z0-9=?+&#%_:\"/, {}]"
# - EudraCT e.g. 2010-022945-52
regEuctr <- "[0-9]{4}-[0-9]{6}-[0-9]{2}"
# - CTGOV
regCtgov <- "NCT[0-9]{8}"
# - CTGOV2
regCtgov2 <- regCtgov
# - regIsrctn
regIsrctn <- "[0-9][0-9]{7}"
# - CTIS e.g. 2022-501549-57-00
regCtis <- "[0-9]{4}-[0-9]{6}-[0-9]{2}-[0-9]{2}"
#
# register list
registerList <- c("EUCTR", "CTGOV", "ISRCTN", "CTIS", "CTGOV2")
#### functions ####
#' ctgovVersion
#'
#' Checks for mismatch between label CTGOV and CTGOV2
#' and tries to guess the correct label
#'
#' @param url url or data frame with query term
#' @param register any of the register names
#'
#' @keywords internal
#' @noRd
#'
#' @returns string
#'
#' @examples
#'
#' ctgovVersion("https://www.clinicaltrials.gov/ct2/show/NCT02703272", "")
#' ctgovVersion("https://classic.clinicaltrials.gov/ct2/results?cond=&term=NCT02703272&cntry=", "")
#' ctgovVersion("https://clinicaltrials.gov/ct2/results?cond=&term=NCT02703272&cntry=", "")
#' ctgovVersion("https://classic.clinicaltrials.gov/ct2/show/NCT02703272?term=NCT02703272&draw=2&rank=1")
#' ctgovVersion("https://clinicaltrials.gov/ct2/results?cond=", "")
#'
#' ctgovVersion("https://www.clinicaltrials.gov/search?term=NCT04412252,%20NCT04368728", "")
#' ctgovVersion("term=NCT04412252,%20NCT04368728", "CTGOV2")
#' ctgovVersion("https://www.clinicaltrials.gov/search?distance=50&cond=Cancer", "")
#'
ctgovVersion <- function(url, register) {
# in case the input is from dbQueryHistory
if (!is.atomic(url)) try({url <- url[["query-term"]]}, silent = TRUE)
if (inherits(url, "try-error") || is.null(url)) return(register)
# logic 1
if (grepl(paste0(
"clinicaltrials[.]gov/ct2/|",
# these are classic-specific
"[?&]rsub=|[?&]type=|[?&]rslt=|[?&]gndr=|[?&]recrs=|[?&]phase=|",
"[?&]age=|[?&]cntry=|[?&][a-z]+_[a-z]+="), url)) { # e.g. strd_s
message("* Appears specific for CTGOV Classic website")
return("CTGOV")
}
# logic 2
if (grepl(paste0(
# clear identifiers of CTGOV2
"aggFilters|clinicaltrials[.]gov/(search|study)[/?]|",
"[?&]country=|[:][^/]|%3[aA]"), url)) {
message("* Appears specific for CTGOV REST API 2.0")
return("CTGOV2")
}
# default return
message("Not overruling register label ", register)
return(register)
}
#' ctgovClassicToCurrent
#'
#' Fully translates a user's search query URL from the classic website
#' into a query for the current website, with all search parameters.
#' added to accomodate classic website retirement as of 2024-06-25.
#' Note this function only handles search queries, but not display
#' URLs such as https://clinicaltrials.gov/ct2/show/NCT02703272.
#' The function is to be called by ctrGetQueryUrl(), which turns
#' search and display URLs into queries. See also
#' ./inst/tinytest/more_test_ctrdata_param_checks.R
#'
#' @param url url intended for a search in the classic CTGOV website
#'
#' @keywords internal
#' @noRd
#'
#' @importFrom countrycode countrycode
#' @importFrom utils URLdecode
#'
#' @returns string url suitable for a search current CTGOV website
#'
#' @examples
#'
#' ctgovClassicToCurrent("https://www.clinicaltrials.gov/search?term=NCT04412252,%20NCT04368728")
#' ctgovClassicToCurrent("https://classic.clinicaltrials.gov/ct2/results?cond=&term=NCT02703272&cntry=")
#' ctgovClassicToCurrent("https://clinicaltrials.gov/ct2/results?cond=&term=NCT02703272&cntry=")
#' ctgovClassicToCurrent("https://www.clinicaltrials.gov/search?distance=50&cond=Cancer")
#' ctgovClassicToCurrent("https://classic.clinicaltrials.gov/ct2/results?term=AREA[MaximumAge]+RANGE[0+days,+28+days]")
#'
ctgovClassicToCurrent <- function(url, verbose = TRUE) {
# apiParams is a kind of dictionary for
# mapping classic to current params
#
# - not matched:
# CTGOV2 studyComp
# CTGOV dist
# CTGOV rsub
#
apiParams <- list(
#
# start aggFilters
#
"ages:" = list(
"extract" = c(
"age=0(&|$)",
"age=1(&|$)",
"age=2(&|$)"
),
"replace" = c(
"child",
"adult",
"older"
),
"collapse" = " ",
"out" = character()
),
#
"phase:" = list(
"extract" = c(
"phase=4(&|$)",
"phase=0(&|$)",
"phase=1(&|$)",
"phase=2(&|$)",
"phase=3(&|$)"),
"replace" = c(
"0",
"1",
"2",
"3",
"4"),
"collapse" = " ",
"out" = character()
),
#
"docs:" = list(
"extract" = c(
"u_prot=Y(&|$)",
"u_sap=Y(&|$)",
"u_icf=Y(&|$)"),
"replace" = c(
"prot",
"sap",
"icf"),
"collapse" = " ",
"out" = character()
),
#
"results:" = list(
"extract" = c(
"rslt=With(&|$)",
"rslt=Without(&|$)"),
"replace" = c(
"with",
"without"),
"collapse" = " ",
"out" = character()
),
#
"funderType:" = list(
"extract" = c(
"fund=[013]*[2][013]*(&|$)",
"fund=[123]*[0][123]*(&|$)",
"fund=[023]*[1][023]*(&|$)",
"fund=[012]*[3][012]*(&|$)"),
"replace" = c(
"industry", # 2
"nih", # 0
"fed", # 1
"other"), # 3
"collapse" = " ",
"out" = character()
),
#
"studyType:" = list(
"extract" = c(
"type=Intr",
"type=Obsr",
"type=PReg",
"type=Expn",
"ea_tmt=Yes",
"ea_idv=Yes",
"ea_int=Yes"
),
"replace" = c(
"int", # Interventional
"obs", # Observational
"obs_patreg", # Patient registries
"exp", # Expanded access
"exp_treat", # Treatment IND/Protocol
"exp_indiv", # Individual patients
"exp_inter" # Intermediate-size population
),
"collapse" = " ",
"out" = character()
),
#
"sex:" = list(
"extract" = c(
"gndr=Female",
"gndr=Male"
),
"replace" = c(
"f",
"m"
),
"collapse" = " ",
"out" = character()
),
#
"healthy:" = list(
"extract" = "hlth=Y",
"replace" = "y",
"collapse" = " ",
"out" = character()
),
#
"violation:" = list(
"extract" = "f801=Yes",
"replace" = "y",
"collapse" = " ",
"out" = character()
),
#
"status:" = list(
"extract" = c(
"recrs=a",
"recrs=d",
"recrs=b",
"recrs=e",
"recrs=h",
"recrs=f",
"recrs=g",
"recrs=i",
"recrs=m",
"recrs=c",
"recrs=j",
"recrs=k",
"recrs=l"
),
"replace" = c(
"rec", # Recruiting
"act", # Active, not recruiting
"not", # Not yet recruiting
"com", # Completed
"ter", # Terminated
"enr", # Enrolling by invitation
"sus", # Suspended
"wit", # Withdrawn
"unk", # Unknown
"ava", # Available
"nla", # No longer available
"tna", # Temporarily not available
"afm"), # Approved for marketing
"collapse" = " ",
"out" = character()
),
#
# end aggFilters
#
# dates
"dates" = list(
"extract" = list(
"strd_s=([0-9]{2})/([0-9]{2})/([0-9]{4})(&|$)",
"strd_e=([0-9]{2})/([0-9]{2})/([0-9]{4})(&|$)",
"prcd_s=([0-9]{2})/([0-9]{2})/([0-9]{4})(&|$)",
"prcd_e=([0-9]{2})/([0-9]{2})/([0-9]{4})(&|$)",
"sfpd_s=([0-9]{2})/([0-9]{2})/([0-9]{4})(&|$)",
"sfpd_e=([0-9]{2})/([0-9]{2})/([0-9]{4})(&|$)",
"rfpd_s=([0-9]{2})/([0-9]{2})/([0-9]{4})(&|$)",
"rfpd_e=([0-9]{2})/([0-9]{2})/([0-9]{4})(&|$)",
"lupd_s=([0-9]{2})/([0-9]{2})/([0-9]{4})(&|$)",
"lupd_e=([0-9]{2})/([0-9]{2})/([0-9]{4})(&|$)"
),
"replace" = list(
"start=\\3-\\1-\\2_",
"start=_\\3-\\1-\\2",
"primComp=\\3-\\1-\\2_",
"primComp=_\\3-\\1-\\2",
"firstPost=\\3-\\1-\\2_",
"firstPost=_\\3-\\1-\\2",
"resFirstPost=\\3-\\1-\\2_",
"resFirstPost=_\\3-\\1-\\2",
"lastUpdPost=\\3-\\1-\\2_",
"lastUpdPost=_\\3-\\1-\\2"
),
"collapse" = "@",
"out" = list()
),
#
# translate simple terms
list(
"extract" = c(
"(cond|city|id|intr|lead|locn|outc|spons|state|titles|term)=(.+)(&|$)",
"(cntry)=(.+)(&|$)"
),
"replace" = c(
"&\\1=\\2",
"&country=\\2"
),
"collapse" = "",
"out" = character()
)
#
) # apiParams
## now operate on the input
# mangle input
queryterm <- utils::URLdecode(url)
queryterm <- gsub("[+]", " ", queryterm)
# some specifics found by chance
queryterm <- sub("[?&]recr=Open", "&recrs=b&recrs=a&recrs=c", queryterm)
queryterm <- sub("[?&]recr=Closed", "&recrs=f&recrs=d&recrs=g&recrs=h&recrs=e&recrs=i&recrs=m&recrs=j&recrs=k&recrs=l", queryterm)
# split and focus on parameters
queryterm <- strsplit(queryterm, split = "[&?]")[[1]]
queryterm <- queryterm[!grepl("^https://", queryterm)]
queryterm <- queryterm[queryterm != ""]
# iterate over API terms
for (t in seq_along(queryterm)) {
for (a in seq_along(apiParams)) {
for (i in seq_along(apiParams[[a]][["extract"]])) {
if (grepl(apiParams[[a]][["extract"]][[i]], queryterm[t])) {
item <-
sub(apiParams[[a]][["extract"]][[i]],
apiParams[[a]][["replace"]][[i]],
queryterm[t]
)
apiParams[[a]][["out"]] <-
paste0(
c(apiParams[[a]][["out"]], item),
collapse = apiParams[[a]][["collapse"]]
)
} # if extract
} # extract
} # apiParams
} # queryterm
# merge
apiParams <- sapply(apiParams, "[[", "out")
apiParams <- apiParams[lapply(apiParams, length) > 0L]
# handle two dates parameters into one
if (length(apiParams[["dates"]])) {
tmpSplit <- strsplit(apiParams[["dates"]], "@", fixed = TRUE)[[1]]
apiParams[["dates"]] <- ""
for (t in unique(sub("(.+)=.+", "\\1", tmpSplit))) {
apiParams[["dates"]] <- paste0(c(
apiParams[["dates"]], paste0(
t, "=", sub(
"_+", "_",
paste0(
sub(".+=(.+)", "\\1", tmpSplit[grepl(t, tmpSplit)]),
collapse = "_")),
collapse = "")),
collapse = "&")
}}
# handle parts within aggFilter
for (t in seq_along(apiParams)) {
if (grepl(":", names(apiParams[t]))) apiParams[t] <- paste0(
names(apiParams[t]), paste0(
unique(strsplit(apiParams[[t]], " ")[[1]]), collapse = " ")
)
}
# merge other and aggFilter parts
apiParams <- paste0(
"https://clinicaltrials.gov/search?",
paste0(
unique(apiParams[!grepl(":", names(apiParams))]),
collapse = ""),
"&aggFilters=",
paste0(
unique(apiParams[grepl(":", names(apiParams))]),
collapse = ",")
)
# handle country
if (grepl("[?&]country=[^$&]", apiParams)) {
countryCode <- sub(".+([?&]country=)([A-Z]+)([$&]).*", "\\2", apiParams)
if (countryCode != apiParams) apiParams <-
sub("([?&]country=)([A-Z]+)([$&])",
paste0("\\1", countrycode::countrycode(
countryCode, "iso2c", "iso.name.en"), "\\3"),
apiParams)
}
# prettify
apiParams <- gsub("&&", "&", apiParams)
apiParams <- gsub("&aggFilters=$", "", apiParams)
apiParams <- gsub("search[?]&", "search?", apiParams)
## inform user
# inform user
if (verbose) message(
"Since 2024-06-25, the classic CTGOV servers are no longer available. ",
"Package ctrdata has translated the classic CTGOV query URL from this ",
"call of function ctrLoadQueryIntoDb(queryterm = ...) into a query URL ",
"that works with the current CTGOV2. This is printed below and is also ",
"part of the return value of this function, ctrLoadQueryIntoDb(...)$url. ",
"This URL can be used with ctrdata functions. Note that the fields and ",
"data schema of trials differ between CTGOV and CTGOV2. "
)
# inform user
message(
"\nReplace this URL:\n\n", url,
"\n\nwith this URL:\n\n", apiParams, "\n")
# return
return(apiParams)
} # end ctgovClassicToCurrent
#' Check, write, read cache object for ctrdata
#'
#' @param xname name of variable to read or write
#'
#' @param xvalue value of variable to write
#'
#' @param verbose set to `TRUE` to print debug info
#'
#' @keywords internal
#' @noRd
#'
#' @return value of variable or `NULL` if variable does not exist
#'
ctrCache <- function(xname, xvalue = NULL, verbose = FALSE) {
# hidden environment .ctrdataenv created in zzz.R
# write or overwrite and exit early
if (!is.null(xvalue)) {
assign(x = xname, value = xvalue, envir = .ctrdataenv)
if (verbose) message("- Wrote ", xname, " to cache ")
return(xvalue)
}
# check and read any value for xname variable
if (verbose) message("- Checking cache...")
if (exists(x = xname, envir = .ctrdataenv)) {
tmp <- try(get(x = xname, envir = .ctrdataenv), silent = TRUE)
if (inherits(tmp, "try-error")) return(NULL)
if (verbose) message("- Returning ", xname, " ")
return(tmp)
}
# default
return(NULL)
}
#' Check and prepare nodbi connection object for ctrdata
#'
#' @param con A database connection object, created with
#' \code{nodbi}. See section `1 - Database connection` in
#' \link{ctrdata}.
#'
#' @keywords internal
#'
#' @importFrom nodbi src_sqlite src_duckdb docdb_list
#' @importFrom utils capture.output
#'
#' @return Connection object as list, with collection
#' element under root
#'
ctrDb <- function(con) {
## ensure requirements
if (!requireNamespace("nodbi", quietly = TRUE)) {
stop("Install package 'nodbi' to use this function.",
call. = FALSE)
}
minV <- sub(
".*nodbi[(<>=[:space:]]+([.0-9]+?)\\).*", "\\1",
utils::packageDescription("ctrdata", fields = "Imports")
)
if (!(utils::packageVersion("nodbi") >=
package_version(minV))) {
stop("Update package 'nodbi' to version ",
minV, " or later to use this function.",
call. = FALSE)
}
## check constructor
if (!inherits(con, "docdb_src")) {
stop(
"Database connection object 'con' was not, ",
"but should be created with nodbi.",
call. = FALSE)
}
## postgres
if (inherits(con, "src_postgres")) {
if (is.null(con$collection)) {
stop(
"Specify attribute 'collection' with a table name, using ",
"<nodbi src_postgres object>[[\"collection\"]] <- \"test\"), ",
"for package ctrdata to work.",
call. = FALSE)
}
# add database as element under root
con <- c(
con,
"db" = con$dbname,
"ctrDb" = TRUE)
## return
return(structure(
con,
class = c("src_postgres", "docdb_src")))
}
## sqlite
if (inherits(con, "src_sqlite")) {
if (is.null(con$collection)) {
stop(
"Specify parameter 'collection' with a table name, ",
"such as nodbi::src_sqlite(collection = 'test'), ",
"for package ctrdata to work.",
call. = FALSE)
}
# check
if (inherits(try(nodbi::docdb_list(con), silent = TRUE), "try-error")) {
con <- nodbi::src_sqlite(
dbname = con$dbname,
collection = con$collection)
}
# add database as element under root
con <- c(
con,
"db" = con$dbname,
"ctrDb" = TRUE)
# print warning
if (grepl(":memory:", con$dbname)) {
warning(
"Database not persisting",
call. = FALSE, noBreaks. = FALSE)
}
## return
return(structure(
con,
class = c("src_sqlite", "docdb_src")))
}
## mongo
if (inherits(con, "src_mongo")) {
# rights may be insufficient to call info(),
# hence this workaround that should always
# work and be stable to retrieve name of
# collection in the mongo connection
# suppress... for reconnect info from mongolite
coll <- suppressMessages(utils::capture.output(con$con)[1])
coll <- sub("^.*'(.*)'.*$", "\\1", coll)
# add collection as element under root
con <- c(
con,
"collection" = coll,
"ctrDb" = TRUE)
## return
return(structure(
con,
class = c("src_mongo", "docdb_src")))
}
## duckdb
if (inherits(con, "src_duckdb")) {
if (is.null(con$collection)) {
stop(
"Specify parameter 'collection' with a table name, ",
"such as nodbi::src_duckdb(collection = 'test'), ",
"for package ctrdata to work.",
call. = FALSE)
}
# check
if (inherits(try(nodbi::docdb_list(con), silent = TRUE), "try-error")) {
con <- nodbi::src_duckdb(
dbdir = attr(attr(con$con, "driver"), "dbdir"),
collection = con$collection)
}
# add database as element under root
con <- c(
con,
"db" = attr(attr(con$con, "driver"), "dbdir"),
"ctrDb" = TRUE)
# print warning about nodbi::src_duckdb()
if (grepl(":memory:", attr(attr(con$con, "driver"), "dbdir"))) {
warning(
"Database not persisting\n",
call. = FALSE, noBreaks. = FALSE)
}
## return
return(structure(
con,
class = c("src_duckdb", "docdb_src")))
}
## unprepared for other nodbi adapters so far
stop(
"Please specify in parameter 'con' a database connection ",
"created with nodbi::src_...() functions. ctrdata currently ",
"supports src_mongo(), src_sqlite(), src_postgres() and src_duckdb().",
call. = FALSE)
} # end ctrDb
#' Change type of field based on name of field
#'
#' @param dv a vector of character strings
#'
#' @param fn a field name
#'
#' @return a typed vector, same length as dv
#'
#' @importFrom xml2 xml_text read_html
#' @importFrom lubridate duration ymd_hms dyears dmonths ddays
#'
#' @keywords internal
#' @noRd
#'
typeField <- function(dv, fn) {
# get function name
ft <- typeVars[[fn]]
# expand to function
if (!is.null(ft)) ft <- switch(
typeVars[[fn]],
"ctrInt" = "as.integer(x = x)",
"ctrIntList" = 'sapply(x, function(i) {i[i == "NA"] <- NA; as.integer(i)}, USE.NAMES = FALSE)',
"ctrYesNo" = 'sapply(x, function(i) if (is.na(i)) NA else
switch(i, "Yes" = TRUE, "No" = FALSE, NA), simplify = TRUE, USE.NAMES = FALSE)',
"ctrFalseTrue" = 'if (is.numeric(x)) as.logical(x) else
sapply(x, function(i) switch(i, "true" = TRUE, "false" = FALSE, NA), USE.NAMES = FALSE)',
"ctrDate" = 'as.Date(x, tryFormats =
c("%Y-%m-%d", "%Y-%m", "%Y-%m-%d %H:%M:%S", "%Y-%m-%dT%H:%M:%S",
"%d/%m/%Y", "%Y-%m-%dT%H:%M:%S%z"))',
"ctrDateUs" = 'as.Date(x, tryFormats = c("%b %e, %Y", "%Y-%m-%d", "%Y-%m"))',
"ctrDateTime" = "lubridate::ymd_hms(x)",
"ctrDifftime" = 'as.difftime(as.numeric(lubridate::duration(
tolower(x)), units = "days"), units = "days")',
"ctrDifftimeDays" = "lubridate::ddays(x = as.numeric(x))",
"ctrDifftimeMonths" = "lubridate::dmonths(x = as.numeric(x))",
"ctrDifftimeYears" = "lubridate::dyears(x = as.numeric(x))",
NULL
)
# clean up text
if (is.null(ft)) {
# - if NA as string, change to NA
dv[grepl("^N/?A$|^ND$", dv)] <- NA
# - check if any html entities
htmlEnt <- grepl("&[#a-zA-Z]+;", dv)
# - convert html entities to text and symbols
if (any(htmlEnt) && all(sapply(dv, typeof) == "character")) {
dv[htmlEnt] <-
lapply(dv[htmlEnt], function(i) {
sapply(i, function(ii) {
xml2::xml_text(xml2::read_html(charToRaw(ii)))
}, USE.NAMES = FALSE)
})
}
# - check if possible and convert to numeric
if (all(is.numeric(dv) | is.na(dv))) dv <- as.numeric(dv)
# - collapse unless list structure is heterogenous
rowN1 <- sapply(dv, function(i) is.null(names(i)))
rowN2 <- sapply(names(rowN1), function(i) is.null(i))
rowType <- sapply(dv, function(i) typeof(unlist(i, recursive = FALSE)))
#
if (all(rowN1) &&
all(rowN2) &&
length(unique(rowN1)) <= 1L &&
any(rowType == "character")) {
#
dv <- sapply(dv, function(i) {
i <- gsub("\r", "\n", i)
i <- sub("^Information not present in EudraCT", "", i)
if (length(i) > 1L) {
rowI <- paste0(i[!is.na(i)], collapse = " / ")
if (nchar(rowI)) rowI else NA
} else {
if (length(i) && !is.na(i)) i else NA
}
})
}
# early return
return(dv)
}
# early exit if already date or logical
if (all(sapply(dv, class) %in%
c("logical", "Date", "POSIXct", "POSIXt"))) return(dv)
# record length of input dv for NULL handling
lenDv <- length(dv)
# apply typing function, returning
# if possible a vector over list
tryCatch(
expr = {
dv <- lapply(dv, function(x) {
# - text mangling
x <- ifelse(grepl("Information not present in EudraCT", x), NA, x)
# - give Month Year a Day to allow conversion
if (grepl("date", fn, ignore.case = TRUE)) {
x <- sub("^ClinicalTrials.gov processed this data on ", "", x)
x <- sub("^([a-zA-Z]+) ([0-9]{4})$", "\\1 15, \\2", x)
x <- sub("^([0-9]{4}-[0-9]{2})$", "\\1-15", x)
}
# - apply function to x
eval(parse(text = ft))
})
},
error = function(e) {
message(fn, ": returning untyped values, as ",
ft, " raised an error when applied to ",
paste0(unlist(dv), collapse = " / "))
return(dv)
},
warning = function(w) {
message(fn, ": returning untyped values, as ",
ft, " raised a warning when applied to ",
paste0(unlist(dv), collapse = " / "))
return(dv)
}
)
# exceptional case inform user
if (is.null(dv)) {
warning(paste0(
fn, " could not be typed, please report here: ",
"https://github.com/rfhb/ctrdata/issues"))
dv <- rep_len(NA, lenDv)
}
# make original classes (e.g., Date) reappear
if (!is.list(dv)) dv <- as.list(dv)
if (all(sapply(dv, length) <= 1L)) {
return(do.call("c", dv))
}
# return
return(dv)
} # end typeField
#' Annotate ctrdata function return values
#'
#' @param x object to be annotated
#'
#' @inheritParams ctrDb
#'
#' @keywords internal
#' @noRd
#'
addMetaData <- function(x, con) {
# add metadata
attr(x, "ctrdata-dbname") <- con$db
attr(x, "ctrdata-table") <- con$collection
attr(x, "ctrdata-table-note") <- "^^^ attr ctrdata-table will be removed by end 2024"
attr(x, "ctrdata-collection") <- con$collection
attr(x, "ctrdata-dbqueryhistory") <- dbQueryHistory(
con = con,
verbose = FALSE)
# return annotated object
return(x)
} # end addMetaData
#' ctrMultiDownload
#'
#' @param urls Vector of urls to be downloaded
#' @param destfiles Vector of local file names into which to download
#' @param progress Set to \code{FALSE} to not print progress bar
#' @param resume Logical for dispatching to curl
#' @param multipley Logical for using http/2
#' @param verbose For debug message printing
#'
#' @keywords internal
#' @noRd
#'
#' @return Data frame with columns such as status_code etc
#'
#' @importFrom curl multi_download
#' @importFrom utils URLencode
#' @importFrom jsonlite fromJSON
#'
ctrMultiDownload <- function(
urls,
destfiles,
progress = TRUE,
resume = FALSE,
multiplex = TRUE,
verbose = TRUE) {
stopifnot(length(urls) == length(destfiles))
if (!length(urls)) return(data.frame())
# starting values
numI <- 1L
canR <- resume
# do not again download files that already exist
# or that do not have an (arbitrary) minimal size.
# nchar("Request failed.") is 15L
toDo <- rep.int(TRUE, times = length(urls))
toDo[file.exists(destfiles) &
(is.na(file.size(destfiles)) |
file.size(destfiles) > 20L)] <- FALSE
downloadValue <- data.frame(
"success" = !toDo,
"status_code" = rep.int(200L, length(toDo)),
"resumefrom" = double(length(toDo)),
"url" = urls,
"destfile" = destfiles,
"error" = character(length(toDo)),
"type" = character(length(toDo)),
"modified" = double(length(toDo)),
"time" = double(length(toDo)),
"headers" = character(length(toDo))
)
# remove any duplicates
downloadValue <- unique(downloadValue)
# does not error in case any of the individual requests fail.
# inspect the return value to find out which were successful
# make no more than 3 attempts to complete downloading
while (any(toDo) && numI < 3L) {
args <- c(
urls = list(utils::URLencode(downloadValue$url[toDo])),
destfiles = list(downloadValue$destfile[toDo]),
resume = canR,
progress = progress,
multiplex = multiplex,
c(getOption("httr_config")[["options"]],
accept_encoding = "gzip,deflate,zstd,br")
)
# do download
res <- do.call(curl::multi_download, args)
# check if download successful and CDN is likely to be used
cdnCheck <- (res$status_code %in% c(200L, 206L, 416L)) &
!grepl("[.]json$", res$destfile) &
sapply(res$headers, function(x)
if (length(x) >= 1)
any(grepl("application/json", x))
else FALSE)
# replace url with CDN url
if (any(cdnCheck)) {
message("Redirecting to CDN...")
# get CDN url
res$url[cdnCheck] <- sapply(
res$destfile[cdnCheck],
function(x) jsonlite::fromJSON(x)$url,
USE.NAMES = FALSE,
simplify = TRUE)
# remove files containing CDN url
unlink(res$destfile[cdnCheck])
# reset status
res$status_code[cdnCheck] <- NA
}
# update input
downloadValue[toDo, ] <- res
if (any(grepl(
"annot resume", downloadValue[toDo, "error", drop = TRUE]))) canR <- FALSE
if (inherits(downloadValue, "try-error")) {
stop("Download failed; last error: ", class(downloadValue), call. = FALSE)
}
toDoThis <- is.na(downloadValue$success) |
!downloadValue$success |
!(downloadValue$status_code %in% c(200L, 206L, 416L))
# only count towards repeat attempts if
# the set of repeated urls is unchanged
if (identical(toDo, toDoThis)) numI <- numI + 1L
toDo <- toDoThis
}
if (any(toDo)) {
# remove any files from failed downloads
unlink(downloadValue[toDo, c("destfile"), drop = TRUE])
if (verbose) {
message(
"Download failed for: status code / url(s):"
)
apply(
downloadValue[toDo, c("status_code", "url"), drop = FALSE],
1, function(r) message(r[1], " / ", r[2], "\n", appendLF = FALSE)
)
}
}
return(downloadValue[!toDo, , drop = FALSE])
} # end ctrMultiDownload
#' ctrTempDir
#'
#' create empty temporary directory on localhost for
#' downloading from register into temporary directory
#'
#' @return path to existing directory
#'
#' @keywords internal
#' @noRd
#'
ctrTempDir <- function(verbose = FALSE) {