/
write_idea.R
executable file
·819 lines (648 loc) · 30.8 KB
/
write_idea.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
#' Write IDEA4 results and graphs to local disc
#'
#' This function allows the user to write IDEA4 results either as local PNG files or compiled in reports.
#'
#' @param IDEA_plots an IDEA_plots or IDEA_group_plots object from a \code{plot_idea()} call.
#' @param output_directory the desired output directory for the rendered reports and/or plots. Defaults to "IDEATools_output"
#' @param type the type of output to produce. Can be either "report" to produce compiled reports or "local" to write raw plots as PNG files.
#' @param prefix a prefix which will be added to output files names. Typically, the name of the farm. Ignored in the case of a group analysis : The \code{metadata$MTD_01} field will then be used to identify each farm.
#' @param report_format a string indicating the output format if \code{type = "report"}. Can be a single format (e.g \code{"pdf"}) or multiple formats (e.g. \code{c("pdf","xlsx")}). Possible formats are "pdf", "docx", "pptx" and "xlsx"
#' @param dpi ggplot output resolution.
#' @param append If the input is an xlsx format, should the individual output be appended to the original file ?
#' @param input_file_append file path to an xslx IDEA data spreadsheet
#' @param quiet A command to remove console printing.
#'
#' @details This function automatically creates in \code{output_directory} a subdirectory named after the system date for users to use the same output_directory for multiple diagnosis.
#'
#' Inputs of class \code{IDEA_plots} can be generated by a classic \code{read_idea() |> compute_idea() |> plot_idea()} or \code{old_idea() |> plot_idea()} individual analysis pipelines. Inputs of class \code{IDEA_group_plots} can only be generated by a \code{plot_idea()} call in a group analysis conducted by \code{diag_idea}.
#'
#' In the case of an individual analysis, another subdirectory is created with \code{prefix} as a name so that analyses are not mixed up. The user can choose if output should be raw plots (that can be used in custom reports) or pre-compiled reports with a large variety of available formats.
#'
#' In the case of a group analysis, another subdirectory is created with a name like "Groupe_number_of_farms" so that analyses are not mixed up. The user can again choose if output should be raw plots or pre-compiled reports.
#'
#' If the \code{report_format} argument is set to either "docx" or "pptx", the report will be rendered using the rmarkdown package (and officedown/officer packages for the docx output) using a template stored in this package. For "pdf" output, LaTeX will be called with the rmarkdown package. For "xlsx" output, the openxlsx package will be used to sequentially produce Excel worksheets and files, using an internal R function.
#'
#' Please note that an error will be produced if the input object does not contain all three "dimensions","trees" and "radars" entries in the case of an individual analysis and if \code{type = "report"}.
#'
#' @return Reports and/or raw plots in \code{output_directory}.
#' @export
#'
#' @import data.table
#' @importFrom ggplot2 ggsave
#' @importFrom rmarkdown render
#' @importFrom tibble tibble
#' @importFrom pdftools pdf_convert
#' @importFrom rlang check_installed
#'
#' @examples
#' library(IDEATools)
#' path <- system.file("example_data/idea_example_1.json", package = "IDEATools")
#' my_data <- read_idea(path)
#' computed_data <- compute_idea(my_data)
#' # Only plotting the radars as a minimal example
#' idea_plots <- plot_idea(computed_data, choices = "radars")
#' # Find your temporary directory
#' tempdir <- tempdir()
#'
#' # Export as raw plots to your tempdir
#' write_idea(idea_plots,
#' output_directory = tempdir,
#' type = "local",
#' prefix = "myFarm",
#' dpi = 20 # Can be much higher
#' )
write_idea <- function(IDEA_plots, output_directory, type = c("local", "report"), prefix = NULL, dpi = 320, report_format = "docx", append = FALSE, input_file_append = NULL, quiet = FALSE) {
if (append == TRUE) {
filetype <- tools::file_ext(input_file_append)
if (filetype != "xlsx") {
stop("To append the results to the original file, it should be in xlsx format.")
}
}
# Checks ------------------------------------------------------------------
if (!any(class(IDEA_plots) %in% c("IDEA_group_plots", "IDEA_plots"))) (stop("The input data is not of class 'IDEA_data'"))
# Individual analysis --------------------------------------------------------
if (any(class(IDEA_plots) == "IDEA_plots")) {
# If prefix is null, assign MTD_01
if (is.null(prefix)) {
prefix <- IDEA_plots$data$metadata$MTD_01
}
# Creating Global output directory
output_directory <- file.path(output_directory, Sys.Date(), prefix)
if (!dir.exists(output_directory)) {
dir.create(output_directory, recursive = TRUE)
}
# If export is "local" ----------------------------------------------------
if (any(type == "local")) {
if (!quiet) (message(paste0("Production des ", length(names(IDEA_plots)) - 1, " types de graphiques demand\u00e9s")))
### Dimensions
## If the input has dimensions plots
if (any(names(IDEA_plots) == "dimensions")) {
if (!quiet) (message("Production des graphiques dimensions..."))
## Starting duration estimate
start <- Sys.time()
## Creating directory for dimensions
dimension_plots <- IDEA_plots$dimensions
dimension_directory <- file.path(output_directory, "Dimensions")
if (!dir.exists(dimension_directory)) {
dir.create(dimension_directory, recursive = TRUE)
}
## Creating a table with all paths for ggsave
tab_res <- tibble::tibble(plotname = names(dimension_plots), plot = dimension_plots) |>
transform(plotname = ifelse(plotname == "plot_dimensions", "Dimensions",
ifelse(plotname == "plot_components", "Composantes",
ifelse(plotname == "plot_components_polarised", "Composantes polaris\u00e9es",
ifelse(plotname == "plot_indic_st", "Indicateurs Socio-Territoriaux",
ifelse(plotname == "plot_indic_ec", "Indicateurs Economiques",
ifelse(plotname == "plot_indic_ae", "Indicateurs Agro\u00e9cologiques", plotname)
)
)
)
)
)) |>
transform(prefix = prefix) |>
transform(
widths = c(9.11, 11, 8, 10.69, 10.69, 10.69),
heights = c(5.6, 11.5, 8, 12, 13.5, 9)
) |>
transform(folder = dimension_directory) |>
transform(path = file.path(dimension_directory, paste0(prefix, "_", plotname))) |>
transform(png_path = paste0(path, ".png")) |>
transform(dpi = dpi)
# Iterating
for (i in 1:nrow(tab_res)) {
tab <- tab_res[i, ]
ggplot2::ggsave(tab$plot[[1]], filename = tab$png_path, dpi = tab$dpi, width = tab$widths, height = tab$heights)
}
## Duration estimation
end <- Sys.time()
duration <- round(difftime(end, start, units = "secs"))
if (!quiet) (message(paste0("Les graphiques dimensions ont \u00e9t\u00e9 export\u00e9s \u00e0 l'adresse '", dimension_directory, "' (", duration, "s)")))
}
### If the input has radars plots
if (any(names(IDEA_plots) == "radars")) {
if (!quiet) (message("Production des graphiques radars..."))
## Starting duration estimate
start <- Sys.time()
## Creating directory for radars
radar_plots <- IDEA_plots$radars
radar_directory <- file.path(output_directory, "Propri\u00e9t\u00e9s", "Radars")
if (!dir.exists(radar_directory)) {
dir.create(radar_directory, recursive = TRUE)
}
## Creating a table with all paths for ggsave
tab_res <- tibble::tibble(plotname = names(radar_plots), plot = radar_plots) |>
transform(plotname = ifelse(plotname == "radar_Capacite", "Capacit\u00e9 productive et reproductive de biens et de services",
ifelse(plotname == "radar_Ancrage", "Ancrage Territorial",
ifelse(plotname == "radar_Autonomie", "Autonomie",
ifelse(plotname == "radar_Robustesse", "Robustesse",
ifelse(plotname == "radar_Responsabilite", "Responsabilit\u00e9 globale", plotname)
)
)
)
)) |>
transform(
widths = 16.1,
heights = 7.61
) |>
transform(folder = radar_directory) |>
transform(path = file.path(radar_directory, paste0(prefix, "_", plotname))) |>
transform(png_path = paste0(path, ".png")) |>
transform(dpi = dpi)
# Iterating
for (i in 1:nrow(tab_res)) {
tab <- tab_res[i, ]
ggplot2::ggsave(tab$plot[[1]], filename = tab$png_path, dpi = tab$dpi, width = tab$widths, height = tab$heights)
}
## Duration estimation
end <- Sys.time()
duration <- round(difftime(end, start, units = "secs"))
if (!quiet) (message(paste0("Les graphiques radars ont \u00e9t\u00e9 export\u00e9s \u00e0 l'adresse '", radar_directory, "' (", duration, "s)")))
}
### Trees
## If the input has colored trees
if (any(names(IDEA_plots) == "trees")) {
if (!quiet) (message("Production des arbres \u00e9clair\u00e9s"))
## Starting duration estimate
start <- Sys.time()
## Creating directory for trees
tree_plots <- IDEA_plots$trees
tree_directory <- file.path(output_directory, "Propri\u00e9t\u00e9s", "Arbres \u00e9clair\u00e9s")
if (!dir.exists(tree_directory)) {
dir.create(tree_directory, recursive = TRUE)
}
## Creating a table with all paths for ggsave
tab_res <- tibble::tibble(name = names(tree_plots), itemlist = tree_plots) |>
transform(folder = tree_directory) |>
transform(plotname = ifelse(name == "Capacite", "Capacit\u00e9 productive et reproductive de biens et de services",
ifelse(name == "Ancrage", "Ancrage Territorial",
ifelse(name == "Autonomie", "Autonomie",
ifelse(name == "Robustesse", "Robustesse",
ifelse(name == "Responsabilite", "Responsabilit\u00e9 globale",
ifelse(name == "Global", "Arbre global", name)
)
)
)
)
)) |>
transform(path = file.path(tree_directory, paste0(prefix, "_", plotname))) |>
transform(
png_path = paste0(path, ".png"),
pdf_path = paste0(path, ".pdf")
) |>
transform(dpi = dpi)
## Custom function to iterate (faster than for loop)
export_heuristic_map <- function(prop, itemlist, folder, png_path, pdf_path) {
## List with dimension of trees
heuristic_res <- list(
Robustesse = c(40, 26),
Capacite = c(48, 30),
Autonomie = c(48, 30),
Responsabilite = c(49, 37),
Ancrage = c(33, 20),
Global = c(45, 28)
)
# Dimensions of tree
dim <- heuristic_res[[prop]]
# Save to PDF
ggplot2::ggsave(itemlist, filename = pdf_path, width = dim[1], height = dim[2], device = cairo_pdf)
# Convert to PNG
pdftools::pdf_convert(pdf = pdf_path, format = "png", pages = NULL, filenames = basename(png_path), opw = "", upw = "", verbose = FALSE)
# Move the PNG file to the appropriate folder
if (prop == "Responsabilite") {
exported_name <- basename(list.files(".", pattern = "Respons"))
file.copy(exported_name, png_path, overwrite = TRUE)
file.remove(exported_name)
} else if (prop == "Capacite") {
exported_name <- basename(list.files(".", pattern = "Capacit"))
file.copy(exported_name, png_path, overwrite = TRUE)
file.remove(exported_name)
} else {
file.copy(basename(png_path), png_path, overwrite = TRUE)
file.remove(basename(png_path))
}
}
# Iterating
for (i in 1:nrow(tab_res)) {
tab <- tab_res[i, ]
suppressWarnings(
export_heuristic_map(prop = tab$name, itemlist = tab$itemlist[[1]], tab$folder, tab$png_path, tab$pdf_path)
)
}
## Duration estimation
end <- Sys.time()
duration <- round(difftime(end, start, units = "secs"))
if (!quiet) (message(paste0("Les arbres \u00e9clair\u00e9s ont \u00e9t\u00e9 export\u00e9s \u00e0 l'adresse '", tree_directory, "' (", duration, "s)")))
}
}
# If export is "report" ------------------------------------------------------
if (any(type == "report")) {
rlang::check_installed(c("rmarkdown", "knitr", "openxlsx", "officedown", "gt"), reason = "to produce reports`")
# Reports requires all 3 types of plots
if (length(names(IDEA_plots)) < 4) (stop("Reporting functions requires that all three kind of plots are drawn in previous `plots_idea()` call"))
# Defining a knitting dir in tempdir in case the user doesn't have all permissions in working dir
knitting_dir <- file.path(tempdir(), "IDEATools_reports")
if (!dir.exists(knitting_dir)) (dir.create(knitting_dir))
file.copy(system.file("report/", package = "IDEATools"), knitting_dir, recursive = TRUE)
if (!quiet) {
message(paste0("Production des ", length(report_format), " rapports demand\u00e9s"))
}
### PDF reports
if (any(report_format == "pdf")) {
if (!quiet) (message("Production du rapport PDF..."))
start <- Sys.time()
report_path <- file.path(knitting_dir, "report", "single", "pdf_report.Rmd")
# Defining params
params <- list(
data = IDEA_plots,
dpi = dpi
)
output_file <- paste0("Rapport_individuel_", prefix, ".pdf")
# Render in new env, in knitting dir to avoid full paths
suppressWarnings(rmarkdown::render(report_path,
output_file = output_file,
params = params,
envir = new.env(parent = globalenv()), quiet = TRUE
))
file.copy(file.path(dirname(report_path), output_file), file.path(output_directory, output_file))
end <- Sys.time()
duration <- round(difftime(end, start, units = "secs"))
if (!quiet) {
message(paste0("Le rapport a \u00e9t\u00e9 export\u00e9 \u00e0 l'adresse '", file.path(output_directory, output_file), "' (", duration, "s)"))
}
}
### DOCX reports
if (any(report_format == "docx")) {
if (!quiet) {
message("Production du rapport Microsoft Word...")
}
start <- Sys.time()
report_path <- file.path(knitting_dir, "report", "single", "docx_report.Rmd")
# Defining params
params <- list(
data = IDEA_plots,
outdir = "tmp",
prefix = prefix,
dpi = dpi
)
output_file <- paste0("Rapport_individuel_", prefix, ".docx")
# Render in new env
suppressWarnings(rmarkdown::render(report_path,
output_file = output_file, output_dir = output_directory,
params = params,
envir = new.env(parent = globalenv()), quiet = TRUE
))
end <- Sys.time()
duration <- round(difftime(end, start, units = "secs"))
if (!quiet) {
message(paste0("Le rapport a \u00e9t\u00e9 export\u00e9 \u00e0 l'adresse '", file.path(output_directory, output_file), "' (", duration, "s)"))
}
}
### PPTX reports
if (any(report_format == "pptx")) {
if (!quiet) {
message("Production de la pr\u00e9sentation Microsoft Powerpoint...")
}
start <- Sys.time()
report_path <- file.path(knitting_dir, "report", "single", "pptx_report.Rmd")
# Defining params
params <- list(
data = IDEA_plots,
outdir = "tmp",
prefix = prefix,
dpi = dpi
)
output_file <- paste0("Rapport_individuel_", prefix, ".pptx")
# Render in new env
suppressWarnings(rmarkdown::render(report_path,
output_file = output_file, output_dir = output_directory,
params = params,
envir = new.env(parent = globalenv()), quiet = TRUE
))
end <- Sys.time()
duration <- round(difftime(end, start, units = "secs"))
if (!quiet) {
message(paste0("Le rapport a \u00e9t\u00e9 export\u00e9 \u00e0 l'adresse '", file.path(output_directory, output_file), "' (", duration, "s)"))
}
}
### XLSX reports
if (any(report_format == "xlsx")) {
if (!quiet) {
message("Production du rapport Microsoft Excel...")
}
start <- Sys.time()
output_file <- paste0("Rapport_individuel_", prefix, ".xlsx")
# Using custom function instead of Rmd
excel_report(
IDEAdata = IDEA_plots,
output_dir = output_directory,
output_file = output_file,
outdir = file.path(knitting_dir, "tmp"),
prefix = prefix,
dpi = dpi,
append = append,
input_file_append = input_file_append
)
end <- Sys.time()
duration <- round(difftime(end, start, units = "secs"))
if (!quiet) {
message(paste0("Le rapport a \u00e9t\u00e9 export\u00e9 \u00e0 l'adresse '", file.path(output_directory, output_file), "' (", duration, "s)"))
}
}
}
}
# Group analysis ----------------------------------------------------------
if (any(class(IDEA_plots) == "IDEA_group_plots")) {
## Number of farms
n_farm <- nrow(IDEA_plots$data$metadata)
## Creating output directory
output_directory <- file.path(output_directory, Sys.Date(), paste0("Groupe_", n_farm))
if (!dir.exists(output_directory)) {
dir.create(output_directory, recursive = TRUE)
}
if (any(class(IDEA_plots) == "IDEA_group_plots_ref")) {
## Check format
if (any(type == "report") & any(report_format %in% c("pptx", "docx"))) {
stop("Reference output can only be a pdf or xlsx report")
}
if (any(type == "local")) {
if (!quiet) {
message(paste0("Production des graphiques de groupe..."))
}
### Group graphs
start <- Sys.time()
## Creating directory for groups
group_directory <- file.path(output_directory, "Graphiques")
if (!dir.exists(group_directory)) {
dir.create(group_directory, recursive = TRUE)
}
## Creating a table with all paths for ggsave
tab_res <- tibble::tibble(plotname = names(IDEA_plots), plot = IDEA_plots) |>
subset(plotname != "data") |>
subset(!plotname %in% c("heatmap", "dimensions_histogram")) |>
transform(plotname = ifelse(plotname == "freq_plot", "Fr\u00e9quence_propri\u00e9t\u00e9s",
ifelse(plotname == "dimensions_boxplot", "Distribution_dimensions",
ifelse(plotname == "components_boxplot", "Distribution_composantes",
ifelse(plotname == "indic_ae_boxplot", "Distribution_indicateurs_agroecologiques",
ifelse(plotname == "indic_st_boxplot", "Distribution_indicateurs_socio_territoriaux",
ifelse(plotname == "indic_ec_boxplot", "Distribution_indicateurs_economiques", plotname)
)
)
)
)
)) |>
transform(
widths = c(13, 10, 11.3, 11.9, 11.9, 11.9),
heights = c(5, 6.91, 8.94, 12.5, 14, 11)
) |>
transform(plotname = gsub(x = plotname, pattern = " ", replacement = "_")) |>
transform(path = file.path(group_directory, plotname)) |>
transform(png_path = paste0(path, ".png")) |>
transform(dpi = dpi)
## Custom function to iterate (faster than for loop)
export_metaplot <- function(plotname, plot, widths, heights, png_path, dpi) {
ggplot2::ggsave(plot, filename = png_path, width = widths, height = heights, dpi = dpi)
}
# Iterating
for (i in 1:nrow(tab_res)) {
tab <- tab_res[i, ]
ggplot2::ggsave(tab$plot[[1]], filename = tab$png_path, width = tab$widths, height = tab$heights, dpi = tab$dpi)
}
}
if (any(type == "report")) {
rlang::check_installed(c("rmarkdown", "knitr", "openxlsx", "officedown", "knitr", "gt"), reason = "to produce reports`")
## Creating output directory
if (!dir.exists(output_directory)) {
dir.create(output_directory, recursive = TRUE)
}
# Defining a knitting dir in tempdir in case the user doesn't have all permissions in working directory
knitting_dir <- file.path(tempdir(), "IDEATools_reports")
if (!dir.exists(knitting_dir)) (dir.create(knitting_dir))
file.copy(system.file("report/", package = "IDEATools"), knitting_dir, recursive = TRUE)
if (!quiet) {
message(paste0("Production des ", length(report_format), " rapports demand\u00e9s"))
}
### PDF reports
if (any(report_format == "pdf")) {
if (!quiet) {
message("Production du rapport PDF...")
}
start <- Sys.time()
# Using the HTML report, converted to PDF
report_path <- file.path(knitting_dir, "report", "group", "pdf_group_report_ref.Rmd")
# Defining params
params <- list(
data = IDEA_plots,
dpi = dpi
)
output_file <- paste0("Rapport_groupe_ref_", n_farm, ".pdf")
# Render in new env, in knitting dir to avoid full paths
suppressWarnings(rmarkdown::render(report_path,
output_file = output_file,
params = params,
envir = new.env(parent = globalenv()), quiet = TRUE
))
file.copy(file.path(dirname(report_path), output_file), file.path(output_directory, output_file))
end <- Sys.time()
duration <- round(difftime(end, start, units = "secs"))
if (!quiet) {
message(paste0("Le rapport a \u00e9t\u00e9 export\u00e9 \u00e0 l'adresse '", file.path(output_directory, output_file), "' (", duration, "s)"))
}
}
### XLSX reports
if (any(report_format == "xlsx")) {
if (!quiet) {
message("Production du rapport Microsoft Excel...")
}
start <- Sys.time()
output_file <- paste0("Rapport_groupe_ref_", n_farm, ".xlsx")
# Using custom function instead of Rmd
excel_group_report_reference(
IDEAdata = IDEA_plots,
output_dir = output_directory,
output_file = output_file,
outdir = file.path(knitting_dir, "tmp"),
dpi = dpi
)
end <- Sys.time()
duration <- round(difftime(end, start, units = "secs"))
if (!quiet) {
message(paste0("Le rapport a \u00e9t\u00e9 export\u00e9 \u00e0 l'adresse '", file.path(output_directory, output_file), "' (", duration, "s)"))
}
}
}
# End of ref pipeline
} else {
## Normal pipeline
# If type is "local" --------------------------------------------------------
if (any(type == "local")) {
if (!quiet) {
message(paste0("Production des graphiques de groupe..."))
}
### Group graphs
start <- Sys.time()
## Creating directory for groups
group_directory <- file.path(output_directory, "Graphiques")
if (!dir.exists(group_directory)) {
dir.create(group_directory, recursive = TRUE)
}
## Creating a table with all paths for ggsave
tab_res <- tibble::tibble(plotname = names(IDEA_plots), plot = IDEA_plots) |>
subset(plotname != "data") |>
transform(plotname = ifelse(plotname == "heatmap", "Matrice_propri\u00e9t\u00e9s",
ifelse(plotname == "freq_plot", "Fr\u00e9quence_propri\u00e9t\u00e9s",
ifelse(plotname == "dimensions_histogram", "Histogramme_dimensions",
ifelse(plotname == "dimensions_boxplot", "Distribution_dimensions",
ifelse(plotname == "components_boxplot", "Distribution_composantes",
ifelse(plotname == "indic_ae_boxplot", "Distribution_indicateurs_agroecologiques",
ifelse(plotname == "indic_st_boxplot", "Distribution_indicateurs_socio_territoriaux",
ifelse(plotname == "indic_ec_boxplot", "Distribution_indicateurs_economiques", plotname)
)
)
)
)
)
)
)) |>
transform(
widths = c(10.4, 10, 14.5, 7.95, 11.3, 11.9, 11.9, 11.9),
heights = c(6.82, 5, 8.61, 6.91, 8.94, 12.5, 14, 11)
) |>
transform(plotname = gsub(x = plotname, pattern = " ", replacement = "_")) |>
transform(path = file.path(group_directory, plotname)) |>
transform(png_path = paste0(path, ".png")) |>
transform(dpi = dpi)
## Custom function to iterate (faster than for loop)
export_metaplot <- function(plotname, plot, widths, heights, png_path, dpi) {
ggplot2::ggsave(plot, filename = png_path, width = widths, height = heights, dpi = dpi)
}
# Iterating
for (i in 1:nrow(tab_res)) {
tab <- tab_res[i, ]
ggplot2::ggsave(tab$plot[[1]], filename = tab$png_path, width = tab$widths, height = tab$heights, dpi = tab$dpi)
}
end <- Sys.time()
duration <- round(difftime(end, start, units = "secs"))
if (!quiet) {
message(paste0("Les figures ont bien \u00e9t\u00e9 export\u00e9es dans le r\u00e9pertoire '", file.path(group_directory), "' (", duration, "s)\n"))
}
}
# If export is "report" -----------------------------------------------------
if (any(type == "report")) {
rlang::check_installed(c("rmarkdown", "knitr", "openxlsx", "officedown", "knitr", "gt"), reason = "to produce reports`")
## Creating output directory
if (!dir.exists(output_directory)) {
dir.create(output_directory, recursive = TRUE)
}
# Defining a knitting dir in tempdir in case the user doesn't have all permissions in working directory
knitting_dir <- file.path(tempdir(), "IDEATools_reports")
if (!dir.exists(knitting_dir)) (dir.create(knitting_dir))
file.copy(system.file("report/", package = "IDEATools"), knitting_dir, recursive = TRUE)
if (!quiet) {
message(paste0("Production des ", length(report_format), " rapports demand\u00e9s"))
}
### PDF reports
if (any(report_format == "pdf")) {
if (!quiet) {
message("Production du rapport PDF...")
}
start <- Sys.time()
# Using the HTML report, converted to PDF
report_path <- file.path(knitting_dir, "report", "group", "pdf_group_report.Rmd")
# Defining params
params <- list(
data = IDEA_plots,
dpi = dpi
)
output_file <- paste0("Rapport_groupe_", n_farm, ".pdf")
# Render in new env, in knitting dir to avoid full paths
suppressWarnings(rmarkdown::render(report_path,
output_file = output_file,
params = params,
envir = new.env(parent = globalenv()), quiet = TRUE
))
file.copy(file.path(dirname(report_path), output_file), file.path(output_directory, output_file))
# Actualise for printing
output_file <- paste0("Rapport_groupe_", n_farm, ".pdf")
end <- Sys.time()
duration <- round(difftime(end, start, units = "secs"))
if (!quiet) {
message(paste0("Le rapport a \u00e9t\u00e9 export\u00e9 \u00e0 l'adresse '", file.path(output_directory, output_file), "' (", duration, "s)"))
}
}
### DOCX reports
if (any(report_format == "docx")) {
if (!quiet) {
message("Production du rapport Microsoft Word...")
}
start <- Sys.time()
report_path <- file.path(knitting_dir, "report", "group", "docx_group_report.Rmd")
# Defining params
params <- list(
data = IDEA_plots,
outdir = "tmp",
dpi = dpi
)
output_file <- paste0("Rapport_groupe_", n_farm, ".docx")
# Render in new env
suppressWarnings(rmarkdown::render(report_path,
output_file = output_file, output_dir = output_directory,
params = params,
envir = new.env(parent = globalenv()), quiet = TRUE
))
end <- Sys.time()
duration <- round(difftime(end, start, units = "secs"))
if (!quiet) {
message(paste0("Le rapport a \u00e9t\u00e9 export\u00e9 \u00e0 l'adresse '", file.path(output_directory, output_file), "' (", duration, "s)"))
}
}
### PPTX reports
if (any(report_format == "pptx")) {
if (!quiet) {
message("Production de la pr\u00e9sentation Microsoft Powerpoint...")
}
start <- Sys.time()
report_path <- file.path(knitting_dir, "report", "group", "pptx_group_report.Rmd")
# Defining params
params <- list(
data = IDEA_plots,
outdir = "tmp",
dpi = dpi
)
output_file <- paste0("Rapport_groupe_", n_farm, ".pptx")
# Render in new env
suppressWarnings(rmarkdown::render(report_path,
output_file = output_file, output_dir = output_directory,
params = params,
envir = new.env(parent = globalenv()), quiet = TRUE
))
end <- Sys.time()
duration <- round(difftime(end, start, units = "secs"))
if (!quiet) {
message(paste0("Le rapport a \u00e9t\u00e9 export\u00e9 \u00e0 l'adresse '", file.path(output_directory, output_file), "' (", duration, "s)"))
}
}
### XLSX reports
if (any(report_format == "xlsx")) {
if (!quiet) {
message("Production du rapport Microsoft Excel...")
}
start <- Sys.time()
output_file <- paste0("Rapport_groupe_", n_farm, ".xlsx")
# Using custom function instead of Rmd
excel_group_report(
IDEAdata = IDEA_plots,
output_dir = output_directory,
output_file = output_file,
outdir = file.path(knitting_dir, "tmp"),
dpi = dpi
)
end <- Sys.time()
duration <- round(difftime(end, start, units = "secs"))
if (!quiet) {
message(paste0("Le rapport a \u00e9t\u00e9 export\u00e9 \u00e0 l'adresse '", file.path(output_directory, output_file), "' (", duration, "s)"))
}
}
}
}
}
}