-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathddop_plot.R
1670 lines (1431 loc) · 71.6 KB
/
ddop_plot.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
############################################################################
# FUNCTIONS TO PLOT ANALYSIS ###############################################
############################################################################
############################################################################
# make_docx_table ##########################################################
############################################################################
#' Generate a Word Table with Variable Information
#'
#' This function creates a Word document containing a table with selected variables
#' from a dataset, showing their labels and the percentage of missing values.
#'
#' @param dataset A data frame containing the data.
#' @param variables A character vector of variable names from the dataset.
#' @param path The file path where the Word document will be saved.
#'
#' @return None. The function generates a .docx file at the specified path.
#'
#' @examples
#' # Assuming 'data' is your dataset and 'vars' is the list of variables:
#' make_docx_table(data, vars, "output.docx")
#'
make_docx_table <- function(dataset, variables, path) {
# Retrieve labels for each variable in the dataset
var_labels <- sapply(variables, function(var_name) get_label_by_variable(dataset, var_name))
# Calculate the percentage of missing or negative values for the dataset
neg_perc <- negative_perc(dataset)
perc_minus1 <- neg_perc[[1]]
# Create a data frame with variable names, labels, and percentage of missing values
var_ds <- data.frame(
variable = names(var_labels), # Variable names
label = var_labels, # Corresponding labels
perc_missing = paste(perc_minus1, "%", sep="") # Percentage of missing values
) %>% arrange(Na) # Sort the data frame based on the 'Na' column (if present)
# Convert the data frame to a flextable object for formatting
ft <- flextable(var_ds)
# Create a new Word document
doc <- read_docx()
# Add the flextable to the Word document
doc <- body_add_flextable(doc, ft)
# Save the Word document to the specified path
print(doc, target = path)
}
############################################################################
# make_alluvial_plot #######################################################
############################################################################
#' Generate Alluvial Plots and Export to Word Document
#'
#' This function creates alluvial plots for different waves of data, showing
#' changes in depression status from baseline (BL) to follow-up (FU), and
#' exports them to a Word document.
#'
#' @param dataset A data frame containing the data. It must include variables
#' 'wave', 'euro_d', and 'initial_euro_d'.
#' @param output_file A character string specifying the path where the Word document
#' will be saved. Default is "results/euro_alluvial_plot.docx".
#'
#' @return None. The function generates a .docx file with alluvial plots for each wave.
#'
#' @examples
#' # Assuming 'data' is your dataset:
#' make_alluvial_plot(data, "output.docx")
#'
make_alluvial_plot <- function(dataset, output_file = "results/euro_alluvial_plot.docx") {
# Convert variables to factors
dataset$wave <- as.factor(dataset$wave)
dataset$euro_d <- as.factor(dataset$euro_d)
dataset$initial_euro_d <- as.factor(dataset$initial_euro_d)
# Filter dataset for each wave
w5 <- dataset %>% filter(wave == 5)
w6 <- dataset %>% filter(wave == 6)
w7 <- dataset %>% filter(wave == 7)
# Function to create alluvial plots with subtitle
create_alluvial_plot <- function(data_wave, wave_number) {
ggplot(data = data_wave, aes(axis1 = initial_euro_d, axis2 = euro_d)) +
geom_alluvium(aes(fill = euro_d)) +
geom_stratum() +
geom_text(stat = "stratum", aes(label = after_stat(stratum))) +
theme_minimal() +
scale_x_discrete(limits = c("DEPRESSION BL", "DEPRESSION FU"), expand = c(.05, .05)) +
labs(
y = "", x = "",
title = paste("Alluvial Plot BL vs FU Depression in wave", wave_number),
subtitle = paste("To analyze changes in depression status from baseline to follow-up within Wave", wave_number)
)
}
# Create plots for each wave
alluvial_plot3 <- create_alluvial_plot(w5, 5)
alluvial_plot4 <- create_alluvial_plot(w6, 6)
alluvial_plot5 <- create_alluvial_plot(w7, 7)
# Create a Word document
doc <- read_docx()
# Add the plots to the document
doc <- doc %>%
body_add_gg(value = alluvial_plot3, width = 6.2, height = 4) %>%
body_add_par("") %>%
body_add_gg(value = alluvial_plot4, width = 6.2, height = 4) %>%
body_add_par("") %>%
body_add_gg(value = alluvial_plot5, width = 6.2, height = 4)
# Save the document
print(doc, target = output_file)
}
############################################################################
# make_docx_variable_list ##################################################
############################################################################
#' Generate a Word Document Containing a Variable List
#'
#' This function generates a table in a Word document with a list of variables
#' from a dataset, along with their types, domains, and percentage of missing or
#' negative values. It also includes label descriptions for each variable.
#'
#' @param dataset A data frame containing the data.
#' @param domain_mapping A data frame or tibble mapping variables to their domains.
#' @param var_continue A vector of variable names that are considered continuous.
#' @param var_ord A vector of variable names that are considered ordinal.
#' @param path The file path where the Word document will be saved.
#'
#' @return None. The function generates a .docx file at the specified path.
#'
#' @examples
#' # Assuming 'data' is your dataset and 'domain_map' is the domain mapping:
#' make_docx_variable_list(data, domain_map, continuous_vars, ordinal_vars, "output.docx")
#'
make_docx_variable_list <- function(dataset, domain_mapping, var_continue, var_ord, path) {
# Calculate the percentage of missing or negative values for each variable in the dataset
neg_perc <- negative_perc(dataset)
perc_minus1 <- neg_perc[[1]]
# Create an empty tibble to store the variable information
data <- tibble(
label_variabile = character(), # Variable label
type = character(), # Variable type (numeric, orderable, etc.)
domain = character(), # Domain associated with the variable
labels_variabile = character(), # Labels associated with the variable
perc_minus1 = character() # Percentage of missing/negative values
)
# Loop through each variable in the dataset
for (var_name in names(dataset)) {
print(var_name) # Print the variable name for debugging purposes
# Retrieve the label and the possible values (labels) of the variable
label_var <- get_label_by_variable(dataset, var_name)
labels_var <- get_labels_by_variable(dataset, var_name)
# Convert the labels into a single string, separated by commas
if(length(labels_var) > 1) {
labels_var <- paste(labels_var$label, collapse = ", ")
} else {
labels_var <- as.character(labels_var$label)
}
# Convert the label to character format for uniformity
label_var <- as.character(label_var)
# Find the domain corresponding to the variable from the domain_mapping
domain <- domain_mapping$domain[domain_mapping$variable == var_name]
# Determine the type of variable (numeric, orderable, not orderable)
if (var_name %in% var_continue) {
type = "numeric with -1 categorial"
} else if (var_name %in% var_ord) {
type = "orderable"
} else {
type = "not orderable"
}
# Append the variable information to the tibble
data <- bind_rows(data, tibble(
label_variabile = label_var,
type = type,
domain = domain,
labels_variabile = labels_var,
perc_minus1 = paste(perc_minus1[[var_name]], "%", sep = "")
))
}
# Create a flextable object from the tibble for better formatting
ft <- flextable(data)
# Create a new Word document
doc <- read_docx()
# Add the flextable to the Word document
doc <- body_add_flextable(doc, ft)
# Save the Word document to the specified file path
print(doc, target = path)
}
############################################################################
# make_wave_flag_table #####################################################
############################################################################
#' Generate a Summary Table for a Specific Wave
#'
#' This function creates a summary table for a given wave of data, displaying
#' the occurrence count, average age, and gender distribution (male and female)
#' grouped by the 'flag_cfu' (Cancer FU) variable. The table is formatted using
#' the `flextable` package and includes headers, borders, and aligned columns.
#'
#' @param dataset A data frame containing the data.
#' @param wave The wave number to filter the data.
#'
#' @return A formatted flextable object displaying the summary statistics.
#'
#' @examples
#' # Assuming 'data' is your dataset:
#' make_wave_flag_table(data, 5)
#'
make_wave_flag_table <- function(dataset, wave) {
# Filter the dataset for the specified wave and group by 'flag_cfu'
table <- dataset %>%
filter(wave == !!wave) %>% # Filter data for the given wave
group_by(flag_cfu) %>% # Group by 'flag_cfu' (Cancer FU)
summarize(
occ = n(), # Count the number of occurrences per group
age = round(mean(age_int, na.rm = TRUE), 2), # Calculate mean age and round to 2 decimal places
male = sum(dn042_ == 0, na.rm = TRUE), # Count the number of males (dn042_ == 0)
female = sum(dn042_ == 1, na.rm = TRUE) # Count the number of females (dn042_ == 1)
) %>%
ungroup() %>% # Ungroup the data
flextable() %>% # Convert to flextable for formatting
set_header_labels(
flag_cfu = "Cancer FU", # Set header label for 'flag_cfu'
occ = "N", # Set header label for occurrences
age = "Age", # Set header label for mean age
male = "M", # Set header label for male count
female = "F" # Set header label for female count
) %>%
add_header_row( # Add a header row with the wave information
values = paste("Wave", wave, "Table"), # Dynamic header with wave number
colwidths = 5 # Span the header across 5 columns
) %>%
align(align = "center", part = "header") %>% # Center align the header text
colformat_double(j = "age", digits = 2) %>% # Format the 'age' column to display 2 decimal places
border_outer(part = "all", border = fp_border(color = "black", width = 1, style = "solid")) %>%
border_inner_h(part = "all", border = fp_border(color = "black", width = 1, style = "solid")) %>%
border_inner_v(part = "all", border = fp_border(color = "black", width = 1, style = "solid")) # Add borders around the table
return(table) # Return the formatted flextable
}
############################################################################
# make_wave_condition_table ################################################
############################################################################
#' Generate a Table Summarizing Conditions by Wave
#'
#' This function creates a summary table for a specified wave of data. The table
#' contains counts of individuals in each condition group (condition_fu), along with
#' their average age and gender distribution (male and female).
#'
#' @param dataset A data frame containing the data. It must include the variables
#' 'wave', 'condition_fu', 'age_int', and 'dn042_'.
#' @param wave A specific wave (e.g., 5, 6, or 7) to filter the data.
#'
#' @return A flextable object summarizing the condition, number of occurrences,
#' average age, and the male/female count for the given wave.
#'
#' @examples
#' # Assuming 'data' is your dataset:
#' make_wave_condition_table(data, 5)
#'
make_wave_condition_table <- function(dataset, wave) {
# Filter dataset for the specified wave and group by condition_fu
table <- dataset %>%
filter(wave == !!wave) %>% # Filter for the selected wave
group_by(condition_fu) %>% # Group by condition
summarize(
occ = n(), # Count occurrences in each condition
age = round(mean(age_int, na.rm = TRUE), 2), # Calculate mean age, removing NAs
male = sum(dn042_ == 0, na.rm = TRUE), # Count males (assuming dn042_ == 0 for males)
female = sum(dn042_ == 1, na.rm = TRUE) # Count females (assuming dn042_ == 1 for females)
) %>%
ungroup() %>%
# Create a flextable from the summary data
flextable() %>%
# Set custom column labels for the table
set_header_labels(
condition_fu = "Condition FU", # Rename condition column
occ = "N", # Rename count column
age = "Age", # Rename age column
male = "M", # Rename male count column
female = "F" # Rename female count column
) %>%
# Add a header row with the wave number
add_header_row(
values = paste("Wave", wave, "Table"), # Title for the table header
colwidths = 5 # Span across 5 columns
) %>%
# Center-align the header content
align(align = "center", part = "header") %>%
# Format the 'age' column to show only two decimal places
colformat_double(j = "age", digits = 2) %>%
# Add borders to the table
border_outer(part = "all", border = fp_border(color = "black", width = 1, style = "solid")) %>%
border_inner_h(part = "all", border = fp_border(color = "black", width = 1, style = "solid")) %>%
border_inner_v(part = "all", border = fp_border(color = "black", width = 1, style = "solid"))
return(table) # Return the formatted flextable object
}
############################################################################
# make_wave_euro_table #####################################################
############################################################################
#' Generate a Summary Table of Euro Depression Status by Wave
#'
#' This function creates a summary table that displays the change in depression
#' status from baseline (BL) to follow-up (FU) across a specific wave. It also
#' calculates the count, average age, and gender distribution (male and female)
#' for each depression status combination.
#'
#' @param dataset A data frame containing the data. It must include the variables
#' 'wave', 'initial_euro_d', 'euro_d', 'age_int', and 'dn042_'.
#' @param wave The specific wave (e.g., 5, 6, or 7) to filter the data.
#'
#' @return A flextable object summarizing the baseline to follow-up depression
#' combinations, number of occurrences, average age, and male/female count for the given wave.
#'
#' @examples
#' # Assuming 'data' is your dataset:
#' make_wave_euro_table(data, 5)
#'
make_wave_euro_table <- function(dataset, wave) {
# Filter the dataset for the specified wave
table <- dataset %>%
filter(wave == !!wave) %>% # Filter the dataset for the selected wave
# Create a new column combining initial and follow-up depression status
mutate(euro_combination = paste(initial_euro_d, euro_d, sep = "-")) %>%
# Group the data by the combined depression status
group_by(euro_combination) %>%
# Summarize the data: calculate occurrences, average age, and gender counts
summarize(
occ = n(), # Count the number of occurrences in each combination
age = round(mean(age_int, na.rm = TRUE), 2), # Calculate the mean age, rounded to 2 decimals
male = sum(dn042_ == 0, na.rm = TRUE), # Count the number of males
female = sum(dn042_ == 1, na.rm = TRUE) # Count the number of females
) %>%
ungroup() %>% # Remove the groupings
# Convert the summarized data into a flextable for easy display
flextable() %>%
# Set custom column headers for the table
set_header_labels(
euro_combination = "BL->FU", # Rename the combined depression status column
occ = "N", # Rename the occurrences column
age = "Age", # Rename the age column
male = "M", # Rename the male count column
female = "F" # Rename the female count column
) %>%
# Add a header row with the wave number
add_header_row(
values = paste("Wave", wave), # Title for the table header
colwidths = 5 # Span across 5 columns
) %>%
# Center-align the content in the header row
align(align = "center", part = "header") %>%
# Format the 'age' column to display numbers with 2 decimal places
colformat_double(j = "age", digits = 2) %>%
# Add borders to the table
border_outer(part = "all", border = fp_border(color = "black", width = 1, style = "solid")) %>%
border_inner_h(part = "all", border = fp_border(color = "black", width = 1, style = "solid")) %>%
border_inner_v(part = "all", border = fp_border(color = "black", width = 1, style = "solid"))
# Return the formatted table
return(table)
}
############################################################################
# make_wave_table_docx #####################################################
############################################################################
#' Generate a Word Document with Tables for Multiple Waves
#'
#' This function creates a Word document containing tables summarizing different aspects
#' (e.g., euro depression status, flag status, or condition status) for each wave in
#' the dataset. The user can specify which type of table to generate.
#'
#' @param dataset A data frame containing the data. It must include the variable 'wave'.
#' @param euro A logical value indicating whether to generate tables for euro depression status.
#' @param flag A logical value indicating whether to generate tables for flag status.
#' @param condition A logical value indicating whether to generate tables for condition status.
#' @param output_file A character string specifying the file path where the Word document
#' will be saved.
#'
#' @return None. The function generates a .docx file at the specified path.
#'
#' @examples
#' # Assuming 'data' is your dataset:
#' make_wave_table_docx(data, euro = TRUE, output_file = "euro_tables.docx")
#'
make_wave_table_docx <- function(dataset, euro = FALSE, flag = FALSE, condition = FALSE, output_file = "") {
# Get the unique waves present in the dataset
waves <- unique(dataset$wave)
# Create a new Word document
doc <- read_docx()
# Loop through each wave and create the corresponding table
for (w in waves) {
# Determine which type of table to create based on the input parameters
if (euro == TRUE) {
wave_table <- make_wave_euro_table(dataset, w) # Create euro depression table
} else if (flag == TRUE) {
wave_table <- make_wave_flag_table(dataset, w) # Create flag status table
} else if (condition == TRUE) {
wave_table <- make_wave_condition_table(dataset, w) # Create condition status table
}
# Add the table to the Word document
doc <- body_add_flextable(doc, value = wave_table)
# Add a blank paragraph (newline) between tables for readability
doc <- body_add_par(doc, value = "\n", style = "Normal")
}
# Save the Word document to the specified file path
print(doc, target = output_file)
}
############################################################################
# make_distribution_pdf #####################################################
############################################################################
#' Generate PDF with Variable Distributions
#'
#' This function generates a PDF containing plots of distributions for a list of variables.
#' Variables can be of different types (continuous, ordinal, not ordinal, or euro-related),
#' and different types of plots are created depending on the variable type. The layout of the plots
#' is customizable, and multiple pages can be created in the PDF.
#'
#' @param dataset A data frame containing the dataset.
#' @param variables A vector of variable names for which to create distribution plots.
#' @param var_type A list containing vectors of variable names categorized by type (e.g., 'var_continue', 'var_ord', etc.).
#' @param pdf_name A string specifying the name of the output PDF file.
#' @param width The width of the PDF pages (default = 20).
#' @param height The height of the PDF pages (default = 17).
#' @param per_page The number of plots to include per page.
#' @param layout A vector specifying the layout of plots on each page (e.g., c(2, 2) for 2x2 grid).
#'
#' @return None. The function saves the generated PDF to the specified path.
#'
#' @examples
#' # Example usage:
#' make_distribution_pdf(dataset, variables = c("var1", "var2"), var_type = var_types, pdf_name = "output.pdf", per_page = 4, layout = c(2, 2))
#'
make_distribution_pdf <- function(dataset, variables, var_type, pdf_name, width = 20, height = 17, per_page, layout) {
# Create a new PDF with the specified width, height, and name
pdf(paste("plot/", pdf_name, sep=""), width = width, height = height)
# Calculate the number of pages needed based on the number of variables and per_page
num_pages <- ceiling(length(variables) / per_page)
# Prepare necessary data for plotting
var_occ <- create_var_occ(dataset)
var_continue <- var_type$var_continue
var_euro <- var_type$var_euro
var_ord <- var_type$var_ord
var_not_ord <- var_type$var_not_ord
# Loop through the number of pages
for (page in 1:num_pages) {
plots_page <- list()
start_index <- (page - 1) * per_page + 1
end_index <- min(page * per_page, length(variables))
# Loop through each variable to create its corresponding plot
for (i in start_index:end_index) {
var_name <- variables[i]
neg_perc <- negative_perc(dataset)
perc_minus1 <- neg_perc[[1]]
if (!(var_name %in% var_continue)) {
df_occ <- as.data.frame(var_occ[[var_name]])
names(df_occ) <- c("Value", "Count")
var_labels_df <- get_labels_by_variable(dataset, var_name)
var_labels_df$label <- substr(var_labels_df$label, 1, 30) # Shorten labels to 30 characters
}
# Create plot based on variable type
if (var_name %in% var_euro) {
# For euro variables, create a bar plot with value-labels
df_occ$ValueLabel <- with(var_labels_df, paste(value, "-", label))
df_occ$ValueLabel <- factor(df_occ$ValueLabel, levels = df_occ$ValueLabel)
p <- ggplot(df_occ, aes(x = ValueLabel, y = Count)) +
geom_bar(stat = "identity", fill = "skyblue", color = "black", alpha = 0.5) +
labs(x = paste(var_name, "\n", get_label_by_variable(dataset, var_name), "\n -1:", perc_minus1[[var_name]], "%"), y = "") +
theme_minimal() +
theme(legend.position = "none")
} else if (var_name %in% var_ord) {
# For ordinal variables, create a bar plot by euro status
data_for_plot <- dataset %>%
filter(!is.na(.data[[var_name]]), !is.na(euro_d)) %>%
mutate(var_name = factor(.data[[var_name]]), euro_d = factor(euro_d))
p <- ggplot(data_for_plot, aes(x = var_name, fill = euro_d)) +
geom_bar(color = "black", alpha = 0.5) +
scale_x_discrete(breaks = var_labels_df$value, labels = var_labels_df$label) +
scale_fill_manual(values = c("yes" = "skyblue", "no" = "orange")) +
theme_minimal() +
labs(x = paste(var_name, "\n", get_label_by_variable(dataset, var_name), "\n -1:", perc_minus1[[var_name]], "%"), y = "") +
theme(legend.position = "none", axis.text.x = element_text(angle = 45, hjust = 1))
} else if (var_name %in% var_not_ord) {
# For non-ordinal variables, create a pie chart
if (nrow(var_labels_df) > 0) {
var_labels_df$legend_label <- paste(df_occ$Value, "->", var_labels_df$label)
df_occ$ValueLabel <- with(var_labels_df, paste(value, "->", label))
df_occ$ValueLabel <- factor(df_occ$ValueLabel, levels = df_occ$ValueLabel)
} else {
df_occ$ValueLabel <- as.factor(df_occ$Value)
}
colors <- colorRampPalette(RColorBrewer::brewer.pal(min(9, length(unique(df_occ$ValueLabel))), "Set1"))(length(unique(df_occ$ValueLabel)))
p <- ggplot(df_occ, aes(x = "", y = Count, fill = ValueLabel)) +
geom_bar(stat = "identity", color = "black") +
coord_polar("y", start = 0) +
theme_void() +
scale_fill_manual(values = colors, labels = var_labels_df$legend_label, name = var_name) +
labs(caption = paste(var_name, "\n", get_label_by_variable(dataset, var_name), "\n -1:", perc_minus1[[var_name]], "%"))
} else if (var_name %in% var_continue) {
# For continuous variables, create a density plot
p <- ggplot(dataset, aes(x = !!sym(var_name))) +
geom_density(aes(y = after_stat(count)), fill = "skyblue", alpha = 0.5) +
labs(x = paste(var_name, "\n", get_label_by_variable(dataset, var_name), "\n -1:", perc_minus1[[var_name]], "%"), y = "") +
theme_minimal()
}
# Store the plot in the list
plots_page[[i - start_index + 1]] <- p
}
# Arrange the plots on the page with the specified layout
do.call(grid.arrange, c(plots_page, ncol = layout[1], nrow = layout[2], padding = unit(0.5, "lines")))
}
# Close the PDF device
dev.off()
}
############################################################################
# pre_analysis_plot ########################################################
############################################################################
#' Generate Pre-Analysis Plots for Different Variable Types
#'
#' This function generates distribution plots for various types of variables in a dataset
#' (continuous, euro, ordinal, non-ordinal). It creates separate PDFs for each type of variable,
#' and organizes the plots within each PDF according to a specified layout.
#'
#' @param dataset A data frame containing the dataset.
#' @param var_type A list containing vectors of variable names categorized by type
#' (e.g., 'var_continue', 'var_euro', 'var_ord', 'var_not_ord').
#' @param path A string specifying the directory where the generated PDF files will be saved.
#'
#' @return None. The function saves the generated PDFs to the specified directory.
#'
#' @examples
#' # Example usage:
#' pre_analysis_plot(dataset = data, var_type = var_types, path = "output/")
#'
pre_analysis_plot <- function(
dataset,
var_type,
path = ""
){
var_continue <- var_type$var_continue
var_euro <- var_type$var_euro
var_ord <- var_type$var_ord
var_not_ord <- var_type$var_not_ord
# Generate distribution plots for continuous variables
if(length(var_continue) > 0 ){
make_distribution_pdf(dataset = dataset,
variables = var_continue,
var_type = var_type,
pdf_name = paste(path, "continue_distribution.pdf", sep=""),
width = 20,
height = 17,
per_page = 12,
layout = c(3, 4))
}
# Generate distribution plots for euro variables
if(length(var_euro) > 0 ){
make_distribution_pdf(dataset = dataset,
variables = var_euro,
var_type = var_type,
pdf_name = paste(path, "euro_distribution.pdf", sep=""),
width = 20,
height = 17,
per_page = 12,
layout = c(3, 4))
}
# Generate distribution plots for ordinal variables
if(length(var_ord) > 0 ){
make_distribution_pdf(dataset = dataset,
variables = var_ord,
var_type = var_type,
pdf_name = paste(path, "fill_ord_distribution.pdf", sep=""),
width = 25,
height = 22,
per_page = 12,
layout = c(3, 4))
}
# Generate distribution plots for non-ordinal variables
if(length(var_not_ord) > 0 ){
make_distribution_pdf(dataset = dataset,
variables = var_not_ord,
var_type = var_type,
pdf_name = paste(path, "not_ord_distribution.pdf", sep=""),
width = 25,
height = 22,
per_page = 12,
layout = c(3, 4))
}
}
############################################################################
# make_variancy_barplot_docx################################################
############################################################################
#' Generate Variance Barplots and Export to Word Document
#'
#' This function creates variance barplots for different types of variables
#' (continuous, ordinal, not ordinal, and euro variables) and saves them to a Word document.
#' It computes the variance of each variable in the dataset, creates barplots, and adds them to the document.
#'
#' @param dataset A data frame containing the dataset.
#' @param var_continue A vector of names of continuous variables.
#' @param var_ord A vector of names of ordinal variables.
#' @param var_not_ord A vector of names of non-ordinal variables.
#' @param var_euro A vector of names of euro-related variables.
#' @param path A string specifying the file path where the Word document will be saved.
#' @param width The width of each plot in the document (default = 6).
#' @param height The height of each plot in the document (default = 1.7).
#'
#' @return None. The function generates a .docx file at the specified path.
#'
#' @examples
#' # Example usage:
#' make_variancy_barplot_docx(dataset = data, var_continue = cont_vars, var_ord = ord_vars, var_not_ord = not_ord_vars, var_euro = euro_vars, path = "output.docx")
#'
make_variancy_barplot_docx <- function(
dataset,
var_continue,
var_ord,
var_not_ord,
var_euro,
path,
width = 7,
height = 3
){
# Continuous variables: Compute variance and create barplot
ds <- dataset %>% select(all_of(intersect(var_continue, colnames(dataset))))
# Calcola la varianza per le variabili continue
variancy_ds <- sapply(ds, function(x) if (is.numeric(x)) sd(x, na.rm = TRUE) / mean(x, na.rm = TRUE) * 100 else NA)
# Filtra le variabili valide (con varianza calcolata)
variancy_ds <- data.frame(
variable = names(variancy_ds),
value = variancy_ds
) %>% na.omit()
# Ottieni i nomi leggibili delle variabili
var_names <- sapply(variancy_ds$variable, function(var) {
get_label_by_variable(dataset, var)
})
# Sostituisci i nomi se necessario (opzionale)
var_names_replace <- c("Age", "Children", "Grandchildren", "Teeth missing", "Weight loss (kg)", "BMI")
if (length(var_names) == length(var_names_replace)) {
var_names <- var_names_replace
}
# Aggiorna i nomi delle variabili nel dataset
variancy_ds$variable <- factor(var_names, levels = var_names[order(variancy_ds$value, decreasing = TRUE)])
# Crea il barplot
p1 <- ggplot(variancy_ds, aes(x = variable, y = value)) +
geom_bar(stat = "identity", fill = "blue") +
theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
labs(x = "", y = "Variability", title = "Continuous Variables")
ds <- dataset %>% select(all_of(intersect(var_ord, colnames(dataset))))
# Calcola la variabilità usando l'IQR per le variabili ordinali
variancy_ds <- sapply(ds, function(x) {
data_num <- as.numeric(x)
MAD <- mean(abs(data_num - mean(data_num, na.rm = TRUE)), na.rm = TRUE)
MAD_max <- (max(data_num, na.rm = TRUE) - min(data_num, na.rm = TRUE)) / 2
if (MAD_max != 0) {
MAD / MAD_max * 100
} else {
NA # Variabili non numeriche sono escluse
}
})
# Filtra i risultati non NA e crea un data frame
variancy_ds <- data.frame(
variable = names(variancy_ds),
value = variancy_ds
) %>% na.omit()
# Ottieni i nomi leggibili delle variabili
var_names <- sapply(variancy_ds$variable, function(var) {
get_label_by_variable(dataset, var)
})
var_names_replace <- c(
"Born citizen",
"Part of area",
"Help in trouble",
"Make ends meet",
"Life satisfaction",
"Age limits",
"Out of control",
"Feel left out",
"Do what you want",
"Family prevents",
"Money shortage",
"Look forward",
"Life has meaning",
"Happy looking back",
"Full of energy",
"Many opportunities",
"Good future",
"Computer skills",
"BMI categories",
"Health question 2",
"Limited by health",
"Distance eyesight",
"Use hearing aid",
"Hearing",
"Pain level",
"Replaced teeth",
"Feels lonely",
"Health insurance satisfaction",
"Vigorous activities",
"Moderate activities",
"2+ years with cancer",
"Condition duration",
"Cancer duration"
)
if (length(var_names) == length(var_names_replace)) {
var_names <- var_names_replace
}
# Ordina le variabili in base alla variabilità
variancy_ds$variable <- factor(var_names, levels = var_names[order(variancy_ds$value, decreasing = TRUE)])
# Crea il barplot per le variabili ordinali
p2 <- ggplot(variancy_ds, aes(x = variable, y = value)) +
geom_bar(stat = "identity", fill = "blue") + # Colore delle barre blu
theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
labs(x = "", y = "Variability", title = "Ordinal Variables") +
theme(plot.margin = unit(c(1, 1, 1, 2), "cm")) # Aggiungi margini al grafico
# Non-ordinal variables: Compute variance and create barplot
ds <- dataset %>% select(all_of(var_not_ord))
variancy_ds <- sapply(ds, function(x) {
freq_table <- table(x)
prop_table <- prop.table(freq_table)
k <- length(freq_table)
if (k > 1) {
entropy(prop_table, unit = "log2") / log2(k) * 100
}
})
# Crea un data frame con i risultati
variancy_ds <- data.frame(
variable = names(variancy_ds),
value = variancy_ds
) %>% na.omit()
# Ottieni i nomi leggibili delle variabili (se disponibile)
var_names <- sapply(variancy_ds$variable, function(var) {
if (exists("get_label_by_variable")) {
get_label_by_variable(dataset, var) # Usa la funzione se esiste
} else {
var # Altrimenti usa il nome originale
}
})
var_names_replace <- c(
"Gender",
"Marital status",
"Ever had any siblings",
"Building area",
"Received external help",
"Help given (12 months)",
"Job situation",
"Physical inactivity",
"Country ID",
"Long-term illness",
"Wears glasses/lenses",
"Eyesight reading" ,
"Health limits work",
"Lost weight check",
"Reason lost weight",
"Pain troubled",
"Joint pain",
"Bifocal/progressive lenses",
"Natural teeth",
"Hospital stay (12 months)",
"No doctor due to cost",
"No doctor due to wait",
"Education level (ISCED-97)",
"Depression",
"Cancer in follow-up?",
"Help activities" ,
"5+ drugs/day",
"Hearing aid",
"Activities (last year)",
"Condition",
"Drugs for",
"Difficulties BADL",
"Difficulties IADL",
"Frailty",
"Use of aids",
"Cancer in",
"Pain location",
"Glasses/lenses type"
)
if (length(var_names) == length(var_names_replace)) {
var_names <- var_names_replace
}
# Ordina le variabili in base all'entropia
variancy_ds$variable <- factor(var_names, levels = var_names[order(variancy_ds$value, decreasing = TRUE)])
# Crea il barplot
p3 <- ggplot(variancy_ds, aes(x = variable, y = value)) +
geom_bar(stat = "identity", fill = "blue") +
theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
labs(x = "", y = "Variability", title = "Non-Ordinal Variables")
# Euro variables: Compute variance and create barplot
ds <- dataset %>% select(all_of(var_euro))
variancy_ds <- sapply(ds, function(x) {
freq_table <- table(x)
prop_table <- prop.table(freq_table)
k <- length(freq_table)
if (k > 1) {
entropy(prop_table, unit = "log2") / log2(k) * 100
}
})
# Crea un data frame con i risultati
variancy_ds <- data.frame(
variable = names(variancy_ds),
value = variancy_ds
) %>% na.omit()
# Ottieni i nomi leggibili delle variabili (se disponibile)
var_names <- sapply(variancy_ds$variable, function(var) {
if (exists("get_label_by_variable")) {
get_label_by_variable(dataset, var) # Usa la funzione se esiste
} else {
var # Altrimenti usa il nome originale
}
})
# Rimuovi eventuali testo tra parentesi (opzionale)
var_names <- gsub("\\s*\\(.*\\)", "", var_names)
# Ordina le variabili in base alla variabilità (entropia)
variancy_ds$variable <- factor(var_names, levels = var_names[order(variancy_ds$value, decreasing = TRUE)])
# Crea il barplot
p4 <- ggplot(variancy_ds, aes(x = variable, y = value)) +
geom_bar(stat = "identity", fill = "blue") +
theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
labs(x = "", y = "Variability", title = "Euro Variables")
# Create a new Word document
doc <- read_docx()
# Add the plots to the Word document with headings for each section
doc <- doc %>%
body_add_par("Continuous Variables", style = "heading 1") %>%
body_add_gg(p1, width, height, style = "centered") %>%
body_add_par("Ordinal Variables", style = "heading 1") %>%
body_add_gg(p2, width, height, style = "centered") %>%
body_add_par("Not ordinal Variables", style = "heading 1") %>%
body_add_gg(p3, width, height, style = "centered") %>%
body_add_par("Euro Variables", style = "heading 1") %>%
body_add_gg(p4, width, height, style = "centered")
# Save the Word document to the specified path
print(doc, target = path)
}
############################################################################
# plot_variable_distribution ###############################################
############################################################################
#' Plot Distribution of a Variable
#'
#' This function generates a plot representing the distribution of a given variable from the dataset.
#' The type of plot depends on whether the variable is continuous, ordinal, non-ordinal, or euro-related.
#'
#' @param dataset A data frame containing the dataset.
#' @param var_name The name of the variable to plot.
#' @param domain_mapping A data frame or tibble mapping variables to their types or domains.
#' @param condition_label A label (optional) used for certain conditions (not used in this version but included for flexibility).
#'
#' @return A ggplot object representing the distribution of the variable.
#'
#' @examples
#' # Example usage:
#' plot_variable_distribution(dataset = data, var_name = "age", domain_mapping = domain_map)
#'
plot_variable_distribution <- function(dataset, var_name, domain_mapping, condition_label) {
# Get variable types based on the domain mapping
var_type <- get_var_type(dataset, domain_mapping)
var_continue <- var_type$var_continue
var_euro <- var_type$var_euro
var_ord <- var_type$var_ord
var_not_ord <- var_type$var_not_ord
var_occ <- create_var_occ(dataset)
p <- NULL # Initialize plot variable
# For non-continuous variables, prepare a dataframe of occurrences and labels
if (!(var_name %in% var_continue)) {
df_occ <- as.data.frame(var_occ[[var_name]])
names(df_occ) <- c("Value", "Count")
var_labels_df <- get_labels_by_variable(dataset, var_name)
var_labels_df$label <- substr(var_labels_df$label, 1, 30) # Truncate labels to 30 characters
}
# Create the plot based on the variable type
if (var_name %in% var_ord) {
# Ordinal variable: Create a bar plot
data_for_plot <- dataset %>% mutate(var_name = factor(.data[[var_name]]))
p <- ggplot(data_for_plot, aes(x = var_name)) +
geom_bar(fill = "skyblue", color = "black", alpha = 0.5) +
theme_minimal() +
theme(axis.title = element_blank(), legend.position = "none")
}
else if(var_name %in% var_not_ord){
# Non-ordinal variable: Create a bar plot
data_for_plot <- dataset %>% mutate(var_name = factor(.data[[var_name]]))
p <- ggplot(data_for_plot, aes(x = var_name)) +
geom_bar(fill = "orange", color = "black", alpha = 0.5) +
theme_minimal() +
theme(axis.title = element_blank(), legend.position = "none")
}
else if(var_name %in% var_euro){