-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1_DVEP.Rmd
1589 lines (1305 loc) · 52.8 KB
/
1_DVEP.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
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
---
title: "DVEP Data Analysis"
author: "Gustavo Santos Paiva Laender Moura"
date: "`r format(Sys.Date(), '%d de %B de %Y')`"
output:
html_document
PID: REDCap 1958
project: Effect of Eclipta prostrata (L.) L. (Asteraceae) on bioelectrical impedance
phase angle in adults with grade I obesity (DVEP)
---
# DATA WRANGLING
## Getting started with R
```{r, results = 'hide', message = FALSE, warning = FALSE}
# 1. Getting started with R
## Clear existing data and graphics
rm(list = ls())
graphics.off()
cat("\014") # Clear any pending RStudio sessions or temporary files
## Load necessary libraries
library(tidyverse)
library(readxl)
library(lubridate)
library(stringr)
library(purrr)
library(gt)
library(jmv)
library(skimr)
```
## Read CSV data files (Tidyverse)
```{r, results = 'hide', message = FALSE, warning = FALSE}
# 2. Read CSV data files (Tidyverse)
codebook_dvep <- read_excel(
"Codebooks/codebook_dvep.xlsx",
col_names = TRUE,
col_types = NULL,
na = c("", "NA", "NI", "UNK", "NASK", "ASKU", "INV"),
trim_ws = TRUE,
skip = 0, # Number of lines to skip before reading data
n_max = Inf, # Maximum number of lines to read.
guess_max = 1000
) |>
arrange(index)
codebook_bia <- read_excel(
"Codebooks/codebook_bia.xlsx",
col_names = TRUE,
col_types = NULL,
na = c("", "NA", "NI", "UNK", "NASK", "ASKU", "INV"),
trim_ws = TRUE,
skip = 0, # Number of lines to skip before reading data
n_max = Inf, # Maximum number of lines to read.
guess_max = 1000
) |>
arrange(index)
codebook_structure <- read_csv(
"Codebooks/codebook_structure.csv",
col_names = TRUE) |>
select(
form_name_en:V3
)
codebook_ncit <- read_csv(
"Codebooks/codebook_ncit.csv",
col_names = TRUE)
data <- read_csv(
"Data/data_dvep.csv",
col_names = TRUE,
col_types = NULL,
col_select = NULL,
id = NULL,
locale = default_locale(),
na = c("", "NA", "NI", "UNK", "NASK", "ASKU", "INV"),
quote = "\"",
comment = "",
trim_ws = TRUE,
skip = 0, # Number of lines to skip before reading data
n_max = Inf, # Maximum number of lines to read.
guess_max = 1000,
name_repair = "unique",
num_threads = readr_threads(),
progress = show_progress(),
show_col_types = TRUE,
skip_empty_rows = TRUE,
lazy = should_read_lazy()
)
data_bia_D3 <- read_csv(
"Data/data_bia_D3.csv",
col_names = TRUE)
data_bia_D1 <- read_csv(
"Data/data_bia_D1.csv",
col_names = TRUE)
```
## Remove identifying data from record_id
```{r, results = 'hide', message = FALSE, warning = FALSE}
# 3. Remove identifying data from record_id
data$record_id <- substr(data$record_id,1,2)
data_bia_D3 $File <- substr(data_bia_D3 $File,1,2)
data_bia_D1$File <- substr(data_bia_D1$File,1,2)
```
## Renaming variables
```{r, results = 'hide', message = FALSE, warning = FALSE}
# 4. Renaming variables
# 4.1 data
rename_data <- setNames(object = colnames(data), codebook_dvep$variable)
data <- data |>
rename(!!!rename_data)
rm(rename_data)
# 4.2 bia
rename_bia <- setNames(object = colnames(data_bia_D3 ), codebook_bia$variable)
data_bia_D3 <- data_bia_D3 |>
rename(!!!rename_bia)
data_bia_D1 <- data_bia_D1 |>
rename(!!!rename_bia)
rm(rename_bia)
```
## record_id as.integer
```{r, results = 'hide', message = FALSE, warning = FALSE}
# 5. record_id as.integer
data$record_id <- as.integer(data$record_id)
data_bia_D3 $record_id <- as.integer(data_bia_D3 $record_id)
data_bia_D1$record_id <- as.integer(data_bia_D1$record_id)
```
## Assign labels to variables
```{r, results = 'hide', message = FALSE, warning = FALSE}
# 6. Assign labels to variables with base R attr()
data <- data |>
mutate(across(
all_of(codebook_dvep$variable),
~ {
attr(., "label") <- codebook_dvep$label_pt[codebook_dvep$variable == cur_column()]
.
}
))
data_bia_D3 <- data_bia_D3 |>
mutate(across(
all_of(codebook_bia$variable),
~ {
attr(., "label") <- codebook_bia$label_pt[codebook_bia$variable == cur_column()]
.
}
))
```
## Creating functions
#### filter_variables()
`filter_variables(visit = c("eleg", "V1", "V2", "V3"), include_repeating = NULL, form_name = NULL, filter_included = TRUE)`
Arguments:
- `visit`: A vector of visit names to filter (default: all visits)
- `include_repeating = NULL`
- If NULL, includes all variables
- If 0, does not include repeating variables
- If 1, only shows repeating variables
- `form_name = NULL`: The name of the form to filter on (NULL means no filtering by form)
- `filter_included = TRUE`: Whether to filter by the 'included' column (default: TRUE)
```{r, results = 'hide', message = FALSE, warning = FALSE}
filter_variables <- function(
visit = c("eleg", "V1", "V2", "V3"),
include_repeating = NULL,
form_name = NULL,
filter_included = TRUE
) {
# Validate the 'visit' input: Ensure all provided visit names are valid
if (!all(visit %in% c("eleg", "V1", "V2", "V3"))) {
stop("Invalid visit name. Choose from 'eleg', 'V1', 'V2', or 'V3'.")
}
# Define valid form names for validation
valid_form_names <- c(
"eleg", "demographic", "whoqol", "dass", "ecap", "measures", "bp_limb", "bp",
"bia", "handgrip", "eliminations", "evs", "alcohol", "tobacco", "diet_recall",
"intake", "dates", "allocation", "conditions", "drugs", "old.drugs", "history",
"symptoms", "phy.exam", "labs", "ecg", "compliance", "events", "medical",
"followup", "conclusion"
)
# Validate the 'form_name' input: Ensure it contains only valid form names
if (!is.null(form_name) && !all(form_name %in% valid_form_names)) {
stop("Invalid form_name. Choose from: ", paste(valid_form_names, collapse = ", "))
}
# Filter the 'codebook_dvep' based on the specified criteria
filtered_codebook <- codebook_dvep |>
filter(
# If filter_included is TRUE, filter for rows where 'included' equals 1
if (filter_included) included == 1 else TRUE,
# Retain rows where at least one of the selected visits has a value greater than 0
rowSums(across(all_of(visit))) > 0,
# If 'include_repeating' is specified, filter by the repeating_instrument column
if (!is.null(include_repeating)) repeating_instrument == include_repeating else TRUE,
# If 'form_name' is specified, filter by the form_name_en column
if (!is.null(form_name)) form_name_en == form_name else TRUE
)
# Extract and return the 'variable' column from the filtered codebook
filtered_vars <- filtered_codebook$variable
return(filtered_vars) # Return the filtered variable names
}
```
#### filter_data()
`filter_data <- function( visit = c("eleg", "V1", "V2", "V3"), include_repeating = NULL, form_name = NULL)`
Arguments:
- `visit`: A vector of visit names to filter (default: all visits)
- `include_repeating = NULL`
- If NULL, includes all variables
- If 0, does not include repeating variables
- If 1, only shows repeating variables
- `form_name = NULL`: The name of the form to filter on. **Will only work for repeating instruments.**
```{r, results = 'hide', message = FALSE, warning = FALSE}
## 7.2 filter_data() based on visit, repeating instrument and form
filter_data <- function(
visit = c("eleg", "V1", "V2", "V3"),
include_repeating = NULL,
form_name = NULL) {
# Map visit names to actual event_name values
mapped_visits <- case_when(
visit == "eleg" ~ "eleg_arm_1",
visit == "V1" ~ "1visit_arm_1",
visit == "V2" ~ "2visit_arm_1",
visit == "V3" ~ "3visit_arm_1",
TRUE ~ visit
)
# Map form_name to repeat_instrument values using a case_when structure
mapped_form_name <- if (!is.null(form_name)) {
case_when(
form_name == "eleg" ~ "elegibilidade",
form_name == "demographic" ~ "dados_demogrficos",
form_name == "whoqol" ~ "questionrio_qualidade_de_vida",
form_name == "dass" ~ "escore_de_depresso_ansiedade_e_estresse",
form_name == "ecap" ~ "escala_de_compulso_alimentar",
form_name == "measures" ~ "antropometria",
form_name == "bp_limb" ~ "presso_arterial_determinao_do_membro_de_referncia",
form_name == "bp" ~ "presso_arterial",
form_name == "bia" ~ "impedncia_bioeltrica_corporal",
form_name == "handgrip" ~ "fora_de_preenso_palmar",
form_name == "eliminations" ~ "avaliao_nutricional",
# form_name == "allergies" ~ "alergia_alimentar",
form_name == "evs" ~ "exercise_vital_sign",
form_name == "alcohol" ~ "consumo_alcool",
form_name == "tobacco" ~ "consumo_tabaco",
form_name == "diet_recall" ~ "recordatrio_alimentar",
form_name == "intake" ~ "avaliao_da_ingesto_alimentar",
form_name == "dates" ~ "datas_importantes",
form_name == "allocation" ~ "nmero_do_participante",
form_name == "conditions" ~ "comorbidades",
form_name == "drugs" ~ "medicamentos_de_uso_habitual",
form_name == "old.drugs" ~ "medicamentos_prvios",
form_name == "history" ~ "antecedentes_pessoais",
form_name == "symptoms" ~ "sintomas",
form_name == "phy.exam" ~ "exame_fsico",
form_name == "labs" ~ "exames_laboratoriais",
form_name == "ecg" ~ "eletrocardiograma",
form_name == "compliance" ~ "adeso",
form_name == "events" ~ "eventos_adversos",
form_name == "medical" ~ "avaliao_mdica",
form_name == "followup" ~ "contato_semanal",
form_name == "conclusion" ~ "concluso",
# form_name == "annex" ~ "anexos",
TRUE ~ form_name
)
} else {
NULL
}
# Get the filtered variable names using the filter_variables function
filtered_vars <- filter_variables(visit, include_repeating, form_name)
# Filter the raw data to only include these columns and match event_name and form_name
filtered_data <- data %>%
filter(event_name %in% mapped_visits) %>%
filter(if (!is.null(include_repeating) && include_repeating == 0) is.na(repeat_instrument) | repeat_instrument == "" else TRUE) %>%
filter(if (!is.null(include_repeating) && include_repeating == 1) !is.na(repeat_instrument) & repeat_instrument != "" else TRUE) %>%
filter(if (!is.null(mapped_form_name)) repeat_instrument == mapped_form_name else TRUE) %>%
select(record_id, event_name, repeat_instrument, repeat_instance, all_of(filtered_vars)) %>%
mutate(
repeat_instrument = ifelse(is.na(repeat_instrument), "", repeat_instrument),
repeat_instance = ifelse(repeat_instrument == "", NA, repeat_instance)
)
return(filtered_data)
}
```
#### filter_codebook()
`filter_codebook(form_name = c(...), included = 1)`
Arguments
- `form_name`
- `included = 1`: defaults to 1, filtering variables by `included` column. If set to 0, will include all variables
```{r, results = 'hide', message = FALSE, warning = FALSE}
## 7.3 filter_codebook()
filter_codebook <- function(form_name = c(
"eleg", "tcle", "demographic", "whoqol", "dass", "ecap", "measures",
"bp_limb", "bp", "bia", "handgrip", "eliminations", "allergies",
"evs", "alcohol", "tobacco", "diet_recall", "intake", "dates",
"allocation", "conditions", "drugs", "old.drugs", "history",
"symptoms", "phy.exam", "labs", "ecg", "compliance", "events",
"medical", "followup", "conclusion", "annex"),
included = 1) {
# Ensure input is valid
if (!all(form_name %in% c("eleg", "tcle", "demographic", "whoqol", "dass", "ecap", "measures",
"bp_limb", "bp", "bia", "handgrip", "eliminations", "allergies",
"evs", "alcohol", "tobacco", "diet_recall", "intake", "dates",
"allocation", "conditions", "drugs", "old.drugs", "history",
"symptoms", "phy.exam", "labs", "ecg", "compliance", "events",
"medical", "followup", "conclusion", "annex")))
{
stop("Invalid form name")
}
if (included == 1) {
codebook_form <- codebook_dvep |>
filter(form_name_en %in% form_name & included == 1)
} else {
codebook_form <- codebook_dvep |>
filter(form_name_en %in% form_name)
}
return(codebook_form)
}
```
#### convert_col_type()
`convert_col_type(data, codebook = codebook_dvep)`
Arguments:
- `data`: dataframe to apply the function
- `codebook = codebook_dvep`: codebook source. Defaults to `codebook_dvep`
Tips:
- as.factor(): categorical data where the label (e.g., "6 cápsulas ao dia") is more meaningful than numeric code.
- binary data (0, Não \| 1, Sim):
- Use as.factor() if the "label" (Não or Sim) is important.
- Use as.numeric(as.character()) if you're performing mathematical operations (e.g., calculating proportions, averages).
- For ordinal data (1, Ruim \| 2, Regular \| 3, Boa \| 4, Excelente): use as.factor() with ordered levels (ordered()) if you need to preserve the ranking.
```{r, results = 'hide', message = FALSE, warning = FALSE}
## 7.4 convert_col_type()
convert_col_type <- function(data, codebook = codebook_dvep) {
# Nested function to convert a single column
convert_column <- function(column, type) {
switch(type,
f = as.factor(column), # Factor
o = as.factor(column), # Factor
c = as.character(column), # Character
d = as.numeric(column), # Numeric
i = as.integer(column), # Integer
k = lubridate::ymd(column), # Date (YYYY-MM-DD)
t = lubridate::ymd_hms(column), # Date-Time (YYYY-MM-DD HH:MM:SS)
h = lubridate::hms(column), # Time only (HH:MM:SS)
n = as.numeric(as.character(column)), # Coerce to Numeric
l = as.logical(column), # Logical
D = as.Date(column, format = "%Y-%m-%d"), # Date with specified format
T = as.POSIXct(column, format = "%Y-%m-%d %H:%M:%S"), # Date-Time
column # Default (no change)
)
}
# Apply conversion
data <- data |>
mutate(
across(
.cols = all_of(intersect(colnames(data), codebook$variable)), # Ensures only common variables are processed
.fns = ~ convert_column(.x, codebook$col_types[which(codebook$variable == cur_column())])
)
)
}
convert_col_type(data)
```
#### label_variables()
`label_variables(data, codebook, language = "pt")`
Arguments:
- `data`: dataframe to which function will be applied
- `codebook`: source codebook
- `language = "pt"`: defaults to portuguese (`"pt"`); set `"en"` for english
```{r, results = 'hide', message = FALSE, warning = FALSE}
label_variables <- function(data, codebook, language = "pt") {
# Determine the label column based on the language argument
label_column <- ifelse(language == "en", "label_en", "label_pt")
# Ensure column names are consistent
codebook_vars <- codebook$variable
codebook_labels <- codebook[[label_column]]
# Identify common variables in both data and codebook
common_vars <- intersect(names(data), codebook_vars)
# Loop through the common variables and assign labels
for (var in common_vars) {
label <- codebook_labels[codebook_vars == var]
attr(data[[var]], "label") <- label
}
return(data)
}
```
label_variables2()
```{r, eval=FALSE, echo=FALSE}
label_variables2 <- function(data, codebook, language = "pt") {
# Determine the label column based on the language argument
label_column <- ifelse(language == "en", "label_en", "label_pt")
# Check if the label column exists in the codebook
if (!(label_column %in% names(codebook))) {
stop(paste("Codebook does not contain the column:", label_column))
}
# Ensure column names are consistent
codebook_vars <- trimws(codebook$variable)
codebook_labels <- codebook[[label_column]]
# Identify common variables in both data and codebook
common_vars <- intersect(names(data), codebook_vars)
# Check if there are common variables
if (length(common_vars) == 0) {
stop("No matching variables found between the data and the codebook.")
}
# Loop through the common variables and assign labels
for (var in common_vars) {
# Ensure label is unique
label <- codebook_labels[which(codebook_vars == var)]
if (length(label) != 1) {
warning(paste("Variable", var, "does not have a unique label in the codebook."))
} else {
attr(data[[var]], "label") <- label
}
}
return(data)
}
```
#### label_choices()
`label_choices(data, codebook = codebook_dvep)`
Arguments:
- `data`: dataframe to which function will be applied
- `codebook = codebook_dvep`: source codebook (dafaults to `codebook_dvep`)
```{r, results = 'hide', message = FALSE, warning = FALSE}
## 7.5 label_choices()
label_choices <- function(data, codebook = codebook_dvep) {
# Ensure required libraries are loaded
if (!requireNamespace("dplyr") || !requireNamespace("tidyr") ||
!requireNamespace("stringr") || !requireNamespace("purrr")) {
stop("Required libraries: dplyr, tidyr, stringr, purrr")
}
# 1. Filter codebook for relevant variables with col_types in "f" or "o"
selected_codebook <- codebook |>
filter(
variable %in% colnames(data) & # Variables present in data
col_types %in% c("f", "o") # col_types in "f" or "o"
)
# 2. Parse the `choices` column
parsed_choices <- selected_codebook |>
rowwise() |>
mutate(
parsed = list(
str_split(choices, " \\| ") |> # Split choices by "|"
unlist() |>
map(~ str_split_fixed(.x, ", ", 2) |> # Split by ", " into two columns
as_tibble(.name_repair = "unique") |> # Ensure unique column names
setNames(c("raw_value", "label")) # Name columns
) |>
bind_rows() # Combine into a tibble
)
) |>
select(variable, parsed) |>
unnest(parsed) # Expand parsed choices into rows
# 3. Create lookup tables for selected variables
lookup_tables <- parsed_choices |>
group_by(variable) |>
summarize(
lookup = list(setNames(label, raw_value)), .groups = "drop"
) |>
deframe()
# 4. Replace raw values with labels in data, using "Unmatched" for unmatched values
for (column_name in names(lookup_tables)) {
if (column_name %in% colnames(data)) { # Ensure column exists in data
data[[column_name]] <- recode( # Apply recode using the lookup table
data[[column_name]],
!!!lookup_tables[[column_name]],
.default = "Unmatched" # Set "Unmatched" as the placeholder for unmatched values
)
}
}
# Explicitly return the modified data
return(data)
}
```
## Bioimpedance data
#### Data from first/third visit
Applies to participants who completed the intervention
```{r, results = 'hide', message = FALSE, warning = FALSE}
# 8. Wrangling Bioimpedance data
## 8.1 D3 DATA (contains data from first and third visits for participants who completed the intervention)
### Filter lines for which phaseangle is <> ""
data_bia_D3_filtered <- data_bia_D3 |>
filter(!is.na(phaseangle)) |>
mutate(
date = as.Date(timestamp), # Extract the date
time = format(timestamp, "%H:%M:%S") # Extract the time
) |>
select(all_of(codebook_bia$variable)[codebook_bia$included == 1], date, time) |>
relocate(record_id, date, time, phaseangle, raverage, xcaverage, weight:w_ecwbytbw) |>
arrange(record_id, date, time)
### Group by record_id and date and obtain mean of multiple measurements from the same day
data_bia_D3_filtered <- data_bia_D3_filtered |>
group_by(record_id, date) |>
summarise(
across(c(phaseangle:m_tohimaginary), \(x) mean(x, na.rm = TRUE)),
.groups = "drop"
) |>
group_by(record_id) |> # Add coding for visit number
mutate(
visit = case_when(
date == min(date) ~ 1, # Assign 1 to the earliest date
date == max(date) ~ 3, # Assign 3 to the latest date
TRUE ~ NA_real_ # Default to NA for unexpected cases
),
.after = record_id
)
```
#### Data from first visit
Applies to participants who did not complete the intervention
```{r, results = 'hide', message = FALSE, warning = FALSE}
## 8.2 D1 DATA (data from the first visit for participants who did not complete the intervention)
## Filter lines for which phaseangle is <> ""
data_bia_D1_filtered <- data_bia_D1 |>
filter(!is.na(phaseangle)) |>
mutate(
date = as.Date(timestamp), # Extract the date
time = format(timestamp, "%H:%M:%S") # Extract the time
) |>
select(all_of(codebook_bia$variable)[codebook_bia$included == 1], date, time) |>
relocate(record_id, date, time, phaseangle, raverage, xcaverage, weight:w_ecwbytbw) |>
arrange(record_id, date, time)
### Group by record_id and date and obtain mean of multiple measurements from the same day
data_bia_D1_filtered <- data_bia_D1_filtered |>
group_by(record_id, date) |>
summarise(
across(c(phaseangle:m_tohimaginary), \(x) mean(x, na.rm = TRUE)),
.groups = "drop"
) |>
group_by(record_id) |> # Add coding for visit number
mutate(
visit = case_when(
date == min(date) ~ 1, # Assign 1 to the earliest date
date == max(date) ~ 3, # Assign 3 to the latest date
TRUE ~ NA_real_ # Default to NA for unexpected cases
),
.after = record_id
)
### Selecting BIA data from D1 not present in D3
data_bia_D1_filtered <- data_bia_D1_filtered |>
filter(
record_id %in% setdiff(1:75, data_bia_D3_filtered$record_id)
)
```
#### Merging to single tibble
```{r, results = 'hide', message = FALSE, warning = FALSE}
## 8.3 MERGE D1/D3 BIA data into a single tibble
data_bia <- bind_rows(
data_bia_D1_filtered, data_bia_D3_filtered
) |>
mutate(
visit = as.integer(visit)
) |>
arrange(
record_id, visit
) |>
ungroup()
### label_variables
data_bia <- label_variables(data_bia, codebook_bia)
```
#### Drop intermediate tibbles
```{r, results = 'hide', message = FALSE, warning = FALSE}
# 8.4. DROP intermediate tibbles
rm(data_bia_D1)
rm(data_bia_D1_filtered)
rm(data_bia_D3)
rm(data_bia_D3_filtered)
```
## Wrangling DVEP REDCap data
#### Adding NCIT labels
```{r, results = 'hide', message = FALSE, warning = FALSE}
## 9.2 Repeating instruments
### 9.2.1. Concatenating NCIT labels (from codebook_ncit) to NCIT codes
#### Conditions (commorbidities)
I21_conditions_R <- filter_data("eleg",1,"conditions") |>
left_join(
codebook_ncit |> select(ncit_code, descriptive),
# by = c("common_comorbidities" = "ncit_code")
join_by(common_comorbidities == ncit_code)
) |>
relocate(
descriptive, .after = common_comorbidities
)
I21_conditions_R <- label_variables(I21_conditions_R, codebook_dvep)
#### Drugs in regular use
I22_drugs_R <- filter_data("eleg",1,"drugs") |>
left_join(
codebook_ncit |> select(ncit_code, descriptive),
join_by(drugs_sql == ncit_code)
) |>
relocate(
descriptive, .after = drugs_sql
)
I22_drugs_R <- label_variables(I22_drugs_R, codebook_dvep)
# # 1.3 Previous drugs
# I23_old_drugs_R <- filter_data("eleg",1,"old.drugs") |>
# left_join(
# codebook_ncit |> select(ncit_code, descriptive),
# join_by(common_previous_medications == ncit_code)
# )|>
# relocate(
# descriptive, .after = common_previous_medications
# )
#
# # 1.4 Past medical conditions
# I24_old_conditions_R <- filter_data("eleg",1,"history") |>
# left_join(
# codebook_ncit |> select(ncit_code, descriptive),
# join_by(common_medical_history == ncit_code)
# )|>
# relocate(
# descriptive, .after = common_medical_history
# )
# Most common comorbidities
# I21_conditions_R |>
# group_by(common_comorbidities, descriptive) |>
# count(common_comorbidities, sort = TRUE, name = "frequency") |>
# mutate(percentage = round((frequency/75 * 100),1)) |>
# view()
# NCIT Condition
# C3117 Hipertensão 18 24 *1
# C26696 Ansiedade 16 21.3
# C37967 Hipercolesterolemia 16 21.3 *2
# C37971 Hipertrigliceridemia 13 17.3 *2
# C113101 Resistência à insulina 11 14.7 *3
# C26800 Hipotireoidismo 9 12
# C89715 Enxaqueca 8 10.7
# C114667 SOP 7 9.3
# C26747 DM2 7 9.3 *3
# Most common drugs
# ```{r, eval = FALSE}
# I22_drugs_R |>
# group_by(drugs_sql, descriptive) |>
# count(drugs_sql, sort = TRUE, name = "frequency") |>
# mutate(percentage = round((frequency/75 * 100),1)) |>
# view()
```
#### Exclusive variables from Eleg/D1 `data_d1_exclusive`
```{r, results = 'hide', message = FALSE, warning = FALSE}
## 9.1 Eclusive variables from Eleg/D1 (`data_d1_exclusive`) to be replicated to d2 and d3
eleg_exclusive <- filter_data("eleg",0) |>
mutate(
intervention_duration = as.numeric(conclusion_date - intervention_start_date)
)|>
select(record_id, allocation_group, completed_intervention, intervention_duration, non_completion_reason, age, sex)
visit_1_exclusive <- filter_data("V1",0) |>
select(
record_id,
race:income_level
) |>
# codebook_dvep$choices[codebook_dvep$variable == "race"]
# [1] "c41260, Asiático | c41261, Branco origem europeia | c128994, Branco origem América do Sul | c16352, Negro | c17998, desconhecido | c17649, Outro"
mutate(
race = if_else(race == "c41261", "c128994", race)
)
data_d1_exclusive <- eleg_exclusive |>
left_join(
visit_1_exclusive,
by = join_by(record_id)
)
rm(eleg_exclusive)
rm(visit_1_exclusive)
```
### Repeating instruments
#### Creating relevant binary variables\*
Hypertension
```{r, results = 'hide', message = FALSE, warning = FALSE}
### 9.3.1 HYPERTENSION
#### Extract record IDs associated with hypertension diagnosis
hypertension_conditions <- I21_conditions_R |>
filter(str_detect(common_comorbidities, "C3117")) |>
pull(record_id)
#### Extract record IDs associated with antihypertensive drugs
hypertension_drugs <- I22_drugs_R |>
filter(str_detect(drugs_sql,
"C66869|C29098|C61635|C47640_2|C28836|C29254|C62027|C62027_2"
)
) |>
pull(record_id)
#### Assign hypertension based on conditions or drugs
data_d1_exclusive <- data_d1_exclusive |>
mutate(hypertension = if_else(
record_id %in% hypertension_conditions,
1,
if_else(
record_id %in% hypertension_drugs,
1,
0
)
))
rm(hypertension_conditions)
rm(hypertension_drugs)
```
Dyslipidemia
```{r, results = 'hide', message = FALSE, warning = FALSE}
### 9.3.2 DYSLIPIDEMIA
#### Extract record IDs associated with dyslipidemia conditions
dyslipidemia_conditions <- I21_conditions_R |>
filter(str_detect(common_comorbidities, "C37967|C37971")) |>
pull(record_id)
#### Extract record IDs associated with antilipemic drugs
dyslipidemia_drugs <- I22_drugs_R |>
filter(str_detect(drugs_sql,
"C29454|C66523_2|C47529|C61527|C87471"
)
) |>
pull(record_id)
#### Assign dyslipidemia based on conditions or drugs
data_d1_exclusive <- data_d1_exclusive |>
mutate(dyslipidemia = if_else(
record_id %in% dyslipidemia_conditions,
1,
if_else(
record_id %in% dyslipidemia_drugs,
1,
0
)
))
rm(dyslipidemia_conditions)
rm(dyslipidemia_drugs)
```
Insulin resistance
```{r, results = 'hide', message = FALSE, warning = FALSE}
### 9.3.3 INSULIN RESISTANCE
#### Extract record IDs associated with insulin resistance or diabetes
insulin_conditions <- I21_conditions_R |>
filter(str_detect(common_comorbidities, "C113101|C26747")) |>
pull(record_id)
#### Extract record IDs associated with anti-hyperglycemic / hypoglycemic drugs
insulin_drugs <- I22_drugs_R |>
filter(str_detect(drugs_sql,
"C61612|C61612_2|C87618|C180533"
)
) |>
pull(record_id)
#### Assign dyslipidemia based on conditions or drugs
data_d1_exclusive <- data_d1_exclusive |>
mutate(insulin = if_else(
record_id %in% insulin_conditions,
1,
if_else(
record_id %in% insulin_drugs,
1,
0
)
))
rm(insulin_conditions)
rm(insulin_drugs)
```
Drugs that might induce weight loss
```{r, results = 'hide', message = FALSE, warning = FALSE}
### 9.3.4 DRUGS THAT MIGHT INDUCE WEIGHT LOSS
#### Extract record IDs
drugs_w_loss <- I22_drugs_R |>
filter(str_detect(drugs_sql,
"C61939|C62012|C506_1|C1278_2|C1278_1|C1278_3|C47764_1|C47764_2|C61680"
)
) |>
pull(record_id)
#### Assign drugs_w_loss based on drugs
data_d1_exclusive <- data_d1_exclusive |>
mutate(drugs_w_loss = if_else(
record_id %in% drugs_w_loss, 1, 0)
)
rm(drugs_w_loss)
```
Drugs that might induce weight gain
```{r, results = 'hide', message = FALSE, warning = FALSE}
### 9.3.5 DRUGS THAT MIGHT INDUCE WEIGHT GAIN
#### Extract record IDs
drugs_w_gain <- I22_drugs_R |>
filter(str_detect(drugs_sql,
"C61879|C62005|C61917_2|C29416|C29536_2"
)
) |>
pull(record_id)
#### Assign drugs_w_loss based on drugs
data_d1_exclusive <- data_d1_exclusive |>
mutate(drugs_w_gain = if_else(
record_id %in% drugs_w_gain, 1, 0)
)
rm(drugs_w_gain)
```
\*Relevant binary variables:
- Hypertension present if: C3117 Hipertensão C66869 Losartana C29098 Hidroclorotiazida C61635 Anlodipino C47640_2 Olmesartana C28836 Atenolol C29254 Metoprolol C62027 Enalapril 10 mg C62027_2 Enalapril 20 mg
- Dyslipidemia present if: C37967 Hipercolesterolemia C37971 Hipertrigliceridemia C29454 Sinvastatina C66523_2 Rosuvastatina C47529 Ezetimiba C61527 Atorvastatina C87471 Ciprofibrato
- Insulin resistance present if: C113101 Resistência insulínica C26747 DM2 C61612 Metformina 500 mg C61612_2 Metformina 850 mg C87618 Gliclazida 30 mg C180533 Empagliflozin/Linagliptin
- Drugs that might induce weight loss C61939 Sertralina C62012 Bupropiona C506_1 Fluoxetina C1278_2 Venlafaxina 75 mg C1278_1 Venlafaxina 37,5 mg C1278_3 Venlafaxina 150 mg C47764_1 Topiramato 25 mg C47764_2 Topiramato 50 mg C61680 Citalopram 20 mg
- Drugs that might induce weight gain C61879 Paroxetina 20 mg C62005 Amitriptilina 25 mg C61917_2 Quetiapina 50 mg C29416 Risperidona 2 mg C29536_2 Ácido Valpróico 250 mg "C61879\|C62005\|C61917_2\|C29416\|C29536_2"
###### Wrapping up `data_d1_exclusive`
```{r, results = 'hide', message = FALSE, warning = FALSE}
data_d1_exclusive <- label_choices(data_d1_exclusive, codebook_dvep)
data_d1_exclusive <- convert_col_type(data_d1_exclusive, codebook_dvep)
data_d1_exclusive <- data_d1_exclusive |>
mutate(
hypertension = as.factor(hypertension),
dyslipidemia = as.factor(dyslipidemia),
insulin = as.factor(insulin),
drugs_w_loss = as.factor(drugs_w_loss),
drugs_w_gain = as.factor(drugs_w_gain)
)
data_d1_exclusive <- label_variables(data_d1_exclusive, codebook_dvep)
```
#### Lab exames
```{r, results = 'hide', message = FALSE, warning = FALSE}
I27_labs_R <- filter_data(c("V1","V2","V3"),1,"labs") |>
mutate(
visit = case_when(
event_name == "1visit_arm_1" ~ 1,
event_name == "2visit_arm_1" ~ 2,
event_name == "3visit_arm_1" ~ 3
),
.after = record_id
)|>
select(-event_name, -repeat_instrument, -repeat_instance, -labs_checked_results_yn)
```
#### Compliance
```{r, results = 'hide', message = FALSE, warning = FALSE}
compliance_V2 <- data |>
select(
record_id, event_name,
filter_variables("V2",1,"compliance")
) |>
filter(event_name == "2visit_arm_1" & cp_compliance_complete == 2) |>
left_join(data |>
filter(event_name == "eleg_arm_1" & !is.na(intervention_start_date)) |>
select(record_id,intervention_start_date, conclusion_date),
by = join_by(record_id)
) |>
left_join(data |>
filter(event_name == "2visit_arm_1" & !is.na(evaluation_date)) |>
select(record_id,evaluation_date),