cute_little_R_functions.R 1 MB
Newer Older
Gael  MILLOT's avatar
Gael MILLOT committed
1
2
################################################################
##                                                            ##
Gael's avatar
Gael committed
3
##     CUTE FUNCTIONS                                         ##
Gael  MILLOT's avatar
Gael MILLOT committed
4
5
6
7
8
##                                                            ##
##     Gael A. Millot                                         ##
##                                                            ##
##                                                            ##
################################################################
Gael  MILLOT's avatar
Gael MILLOT committed
9
10


11
# color palette: see https://github.com/EmilHvitfeldt/r-color-palettes
Gael  MILLOT's avatar
Gael MILLOT committed
12
# https://usethis.r-lib.org/ and usethat also
13
14
# ERROR: this line tempo.log <- suppressWarnings(sapply(lapply(lapply(tempo.arg, FUN = get, env = sys.nframe(), inherit = FALSE), FUN = is.na), FUN = any)) & lapply(lapply(tempo.arg, FUN = get, env = sys.nframe(), inherit = FALSE), FUN = length) == 1L does not work is no argument provided. Example fun_secu(). Fiw it everywhere

15
16
17
18
19
20
21
22
23
24
25
26
27
28
## LAST ROUND OF FORMATTING:
# 1) Arguments: one per line
# 2) Description:
# first capital letter everywhere
# AIM
# WARNINGS
# ARGUMENTS
# Update all argument description, saying, character vector, etc, as in fun_gg_boxplot
# RETURN
# Update as in fun_gg_boxplot
# REQUIRED PACKAGES
# REQUIRED FUNCTIONS FROM THE cute PACKAGE
# EXAMPLE
# one example of the example cheet
29
# see http
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
# DEBUGGING
# one updated
# 3) Categ (see fun_gg_boxplot for inside code)
# function name
# must have arg.user.setting
# end function name

# required function checking
# see boxplot
# end required function checking

# reserved words (to avoid bugs)
# end reserved words (to avoid bugs)

# arg with no default values
# see boxplot
# end arg with no default values

# argument primary checking
# end argument primary checking

# second round of checking and data preparation
# management of NA arguments
# must have arg.user.setting
# end management of NA arguments

# management of NULL arguments
# end management of NULL arguments

# code that protects set.seed() in the global environment
# end code that protects set.seed() in the global environment

# warning initiation
# end warning initiation

# other checkings
# end other checkings

# reserved word checking
# end reserved word checking
# end second round of checking and data preparation

# package checking
# end package checking
# main code
# output
# if(warn.print == TRUE & ! is.null(warn)){
# end output
# end main code
# 4) example sheet as in fun_gg_boxplot
# 5) test the function with debugging_tools_for_r_dev
# 6) use fun_test()
82
83
# 7) check all(, na.rm = TRUE) and any(, na.rm = TRUE), notably in if() that does not like NA result
# 8) write at the beginning of the function:
84
85
# todo list check OK
# Check r_debugging_tools-v1.4.R OK
86
# Check fun_test() 20201107 (see cute_checks.docx) OK
87
# example sheet OK 
88
89
90
91
# check all and any OK
# -> clear to go Apollo


92

93
# fun_mat_fill does not recognize half matrix anymore
94
# package: 
Gael  MILLOT's avatar
Gael MILLOT committed
95
# Templates: https://prettydoc.statr.me/themes.html
96
# http://r-pkgs.had.co.nz/
Gael  MILLOT's avatar
Gael MILLOT committed
97
98
99
# https://pkgdown.r-lib.org/
# https://rdrr.io/github/gastonstat/cointoss/
# doc:https://www.sphinx-doc.org/en/master/man/sphinx-autogen.html considering that https://www.ericholscher.com/blog/2014/feb/11/sphinx-isnt-just-for-python/
Gael  MILLOT's avatar
Gael MILLOT committed
100
101
102
# https://docs.readthedocs.io/en/stable/intro/getting-started-with-sphinx.html
# https://docs.gitlab.com/ee/user/project/pages/
# also register into biotools
103
104
105

# change everywhere: if( ! is.null(arg.check)){

Gael  MILLOT's avatar
Gael MILLOT committed
106
# For heatmap: see https://bioinfo-fr.net/creer-des-heatmaps-a-partir-de-grosses-matrices-en-r
Gael  MILLOT's avatar
Gael MILLOT committed
107

108
109
110
111
# New function: fun_pdf_conc for Rosine code?
# https://stackoverflow.com/questions/17552917/merging-existing-pdf-files-using-r
# https://www.r-bloggers.com/2019/04/join-split-and-compress-pdf-files-with-pdftools/
# https://rdrr.io/cran/staplr/man/staple_pdf.html
Gael  MILLOT's avatar
Gael MILLOT committed
112

Gael  MILLOT's avatar
Gael MILLOT committed
113
################################ OUTLINE ################################
Gael  MILLOT's avatar
Gael MILLOT committed
114
115


Gael  MILLOT's avatar
Gael MILLOT committed
116
117
################ Object analysis    2
######## fun_check() #### check class, type, length, etc., of objects   2
Gael's avatar
Gael committed
118
119
120
121
122
######## fun_secu() #### verif that local variables are not present in other envs   11
######## fun_info() #### recover object information 13
######## fun_head() #### head of the left or right of big 2D objects    15
######## fun_tail() #### tail of the left or right of big 2D objects    16
######## fun_comp_1d() #### comparison of two 1D datasets (vectors, factors, 1D tables) 17
123
######## fun_comp_2d() #### comparison of two 2D datasets (row & col names, dimensions, etc.)   22
Gael's avatar
Gael committed
124
######## fun_comp_list() #### comparison of two lists   29
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
######## fun_test() #### test combinations of argument values of a function and return errors (and graphs)  32
################ Object modification    47
######## fun_name_change() #### check a vector of character strings and modify any string if present in another vector  47
######## fun_df_remod() #### remodeling a data frame to have column name as a qualitative values and vice-versa 48
######## fun_round() #### rounding number if decimal present    51
######## fun_mat_rotate() #### 90° clockwise matrix rotation    53
######## fun_mat_num2color() #### convert a numeric matrix into hexadecimal color matrix    54
######## fun_mat_op() #### assemble several matrices with operation 58
######## fun_mat_inv() #### return the inverse of a square matrix   60
######## fun_mat_fill() #### fill the empty half part of a symmetric square matrix  62
######## fun_permut() #### progressively breaks a vector order  65
######## fun_slide() #### return a computation made on a vector using a sliding window  76
################ Graphics management    85
######## fun_width() #### window width depending on classes to plot 85
######## fun_open() #### open a GUI or pdf graphic window   87
######## fun_prior_plot() #### set graph param before plotting (erase axes for instance)    91
######## fun_scale() #### select nice label numbers when setting number of ticks on an axis 95
######## fun_inter_ticks() #### define coordinates of secondary ticks   100
######## fun_post_plot() #### set graph param after plotting (axes redesign for instance)   105
######## fun_close() #### close specific graphic windows    117
################ Standard graphics  118
######## fun_empty_graph() #### text to display for empty graphs    118
################ gg graphics    120
######## fun_gg_palette() #### ggplot2 default color palette    120
######## fun_gg_just() #### ggplot2 justification of the axis labeling, depending on angle  122
######## fun_gg_get_legend() #### get the legend of ggplot objects  127
######## fun_gg_point_rast() #### ggplot2 raster scatterplot layer  129
######## fun_gg_boxplot() #### ggplot2 boxplot + background dots if required    133
######## fun_gg_scatter() #### ggplot2 scatterplot + lines (up to 6 overlays totally)   133
######## fun_gg_heatmap() #### ggplot2 heatmap + overlaid mask if required  133
######## fun_gg_empty_graph() #### text to display for empty graphs 141
################ Graphic extraction 143
######## fun_trim() #### display values from a quantitative variable and trim according to defined cut-offs 143
######## fun_segmentation() #### segment a dot cloud on a scatterplot and define the dots from another cloud outside the segmentation   152
################ Import 187
######## fun_pack() #### check if R packages are present and import into the working environment    187
######## fun_python_pack() #### check if python packages are present    189
################ Print / Exporting results (text & tables)  192
######## fun_report() #### print string or data object into output file 192
######## fun_get_message() #### return error/warning/other messages of an expression (that can be exported) 195
Gael  MILLOT's avatar
Gael MILLOT committed
165
166


Gael  MILLOT's avatar
Gael MILLOT committed
167
################################ FUNCTIONS ################################
Gael  MILLOT's avatar
Gael MILLOT committed
168

Gael  MILLOT's avatar
Gael MILLOT committed
169
170
171
172
173
174
175

################ Object analysis


######## fun_check() #### check class, type, length, etc., of objects


176
# todo list check OK
Gael's avatar
tempo    
Gael committed
177
# Check r_debugging_tools-v1.4.R OK
178
# Check fun_test() 20201107 (see cute_checks.docx) OK
179
180
181
# example sheet OK 
# check all and any OK
# -> clear to go Apollo
Gael's avatar
tempo    
Gael committed
182
fun_check <- function(
183
184
185
186
187
188
189
190
191
192
193
194
195
196
    data, 
    class = NULL, 
    typeof = NULL, 
    mode = NULL, 
    length = NULL, 
    prop = FALSE, 
    double.as.integer.allowed = FALSE, 
    options = NULL, 
    all.options.in.data = FALSE, 
    na.contain = FALSE, 
    neg.values = TRUE, 
    print = FALSE, 
    data.name = NULL, 
    fun.name = NULL
Gael's avatar
tempo    
Gael committed
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
    # AIM
    # Check the class, type, mode and length of the data argument
    # Mainly used to check the arguments of other functions
    # Check also other kind of data parameters, is it a proportion? Is it type double but numbers without decimal part?
    # If options == NULL, then at least class or type or mode or length argument must be non-null
    # If options is non-null, then class, type and mode must be NULL, and length can be NULL or specified
    # WARNINGS
    # The function tests what is written in its arguments, even if what is written is incoherent. For instance, fun_check(data = factor(1), class = "factor", mode = "character") will return a problem, whatever the object tested in the data argument, because no object can be class "factor" and mode "character" (factors are class "factor" and mode "numeric"). Of note, length of object of class "environment" is always 0
    # If the tested object is NULL, then the function will always return a checking problem
    # Since R >= 4.0.0, class(matrix()) returns "matrix" "array", and not "matrix" alone as before. However, use argument class = "matrix" to check for matrix object (of class "matrix" "array" in R >= 4.0.0) and use argument class = "array" to check for array object (of class "array" in R >= 4.0.0)
    # ARGUMENTS
    # data: object to test
    # class: character string. Either one of the class() result (But see the warning section above) or "vector" or "ggplot2" (i.e., objects of class c("gg", "ggplot")) or NULL
    # typeof: character string. Either one of the typeof() result or NULL
    # mode: character string. Either one of the mode() result (for non-vector object) or NULL
    # length: numeric value indicating the length of the object. Not considered if NULL
    # prop: logical. Are the numeric values between 0 and 1 (proportion)? If TRUE, can be used alone, without considering class, etc.
    # double.as.integer.allowed: logical. If TRUE, no error is reported in the cheking message if argument is set to typeof == "integer" or class == "integer", while the reality is typeof == "double" or class == "numeric" but the numbers strictly have zero as modulo (remainder of a division). This means that i <- 1, which is typeof(i) -> "double" is considered as integer with double.as.integer.allowed = TRUE. WARNING: data%%1 == 0L but not isTRUE(all.equal(data%%1, 0)) is used here because the argument checks for integers stored as double (does not check for decimal numbers that are approximate integers)
    # options: a vector of character strings or integers indicating all the possible option values for the data argument, or NULL. Numbers of type "double" are accepted if they have a 0 modulo
    # all.options.in.data: logical. If TRUE, all of the options must be present at least once in the data argument, and nothing else. If FALSE, some or all of the options must be present in the data argument, and nothing else. Ignored if options is NULL
    # na.contain: logical. Can the data argument contain NA?
    # neg.values: logical. Are negative numeric values authorized? Warning: the default setting is TRUE, meaning that, in that case, no check is performed for the presence of negative values. The neg.values argument is activated only when set to FALSE. In addition, (1) neg.values = FALSE can only be used when class, typeof or mode arguments are not NULL, otherwise return an error message, (2) the presence of negative values is not checked with neg.values = FALSE if the tested object is a factor and the following checking message is returned "OBJECT MUST BE MADE OF NON NEGATIVE VALUES BUT IS A FACTOR"
    # print: logical. Print the message if $problem is TRUE? Warning: set by default to FALSE, which facilitates the control of the checking message output when using fun_check() inside functions. See the example section
    # data.name: character string indicating the name of the object to test. If NULL, use what is assigned to the data argument for the returned message
    # fun.name: character string indicating the name of the function checked (i.e., when fun_check() is used to check the arguments of this function). If non-null, the value of fun.name will be added into the message returned by fun_check()
    # RETURN
    # A list containing:
    # $problem: logical. Is there any problem detected?
    # $text: message indicating the details of the problem, or the absence of problem
    # $object.name: value of the data.name argument (i.e., name of the checked object if provided, NULL otherwise)
    # REQUIRED PACKAGES
    # None
    # REQUIRED FUNCTIONS FROM THE cute PACKAGE
    # None
    # EXAMPLE
    # test <- matrix(1:3) ; fun_check(data = test, print = TRUE, class = "vector", mode = "numeric")
    # see http
    # DEBUGGING
    # data = mean ; class = NULL ; typeof = NULL ; mode = NULL ; length = NULL ; prop = FALSE ; double.as.integer.allowed = FALSE ; options = "a" ; all.options.in.data = FALSE ; na.contain = FALSE ; neg.values = TRUE ; print = TRUE ; data.name = NULL ; fun.name = NULL
    # function name
    # no used in this function for the error message, to avoid env colliding
    # end function name
    # required function checking
    # end required function checking
    # reserved words
    # end reserved words
    # fun.name checked first because required next
    if( ! is.null(fun.name)){ # I have to use this way to deal with every kind of class for fun.name
        if(all(base::class(fun.name) == "character")){ # all() without na.rm -> ok because class(NA) is "logical"
            if(base::length(fun.name) != 1){
                tempo.cat <- paste0("ERROR IN fun_check(): THE fun.name ARGUMENT MUST BE A CHARACTER VECTOR OF LENGTH 1: ", paste(fun.name, collapse = " "))
                stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
            }else if(any(is.na(fun.name))){ # normally no NA with is.na()
                tempo.cat <- paste0("ERROR IN fun_check(): NO ARGUMENT EXCEPT data AND options CAN HAVE NA VALUES\nPROBLEMATIC ARGUMENT IS fun.name")
                stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
            }
        }else{
            tempo.cat <- paste0("ERROR IN fun_check(): THE fun.name ARGUMENT MUST BE A CHARACTER VECTOR OF LENGTH 1") # paste(fun.name, collapse = " ") removed here because does not work with objects like function
            stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
        }
    }
    # end fun.name checked first because required next
    # arg with no default values
    if(missing(data)){
        tempo.cat <- paste0("ERROR IN fun_check()", ifelse(is.null(fun.name), "", paste0(" IN ", fun.name)), ": ARGUMENT data HAS NO DEFAULT VALUE AND REQUIRES ONE")
        stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
    }
    # end arg with no default values
    # argument primary checking
    # source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.7/r_debugging_tools-v1.7.R") ; eval(parse(text = str_basic_arg_check_dev)) # activate this line and use the function to check arguments status
    # end argument primary checking
    # second round of checking and data preparation
    # management of special classes
    basic.class <- c(
        "NULL", # because class(NULL) is "NULL". The NULL aspect will be dealt later
        "logical", 
        "integer", 
        "numeric", 
        # "complex", 
        "character"
        # "matrix", 
        # "array", 
        # "data.frame", 
        # "list", 
        # "factor", 
        # "table", 
        # "expression", 
        # "name", 
        # "symbol", 
        # "function", 
        # "uneval", 
        # "environment", 
        # "ggplot2", 
        # "ggplot_built", 
        # "call"
    )
    tempo.arg.base <-c( # no names(formals(fun = sys.function(sys.parent(n = 2)))) used with fun_check() to be sure to deal with the correct environment
        "class", 
        "typeof", 
        "mode", 
        "length", 
        "prop", 
        "double.as.integer.allowed", 
        "options", 
        "all.options.in.data", 
        "na.contain", 
        "neg.values", 
        "print", 
        "data.name", 
        "fun.name"
    )
    tempo.class <-list( # no get() used to be sure to deal with the correct environment
        base::class(class), 
        base::class(typeof), 
        base::class(mode), 
        base::class(length), 
        base::class(prop), 
        base::class(double.as.integer.allowed), 
        base::class(options), 
        base::class(all.options.in.data), 
        base::class(na.contain), 
        base::class(neg.values), 
        base::class(print), 
        base::class(data.name), 
        base::class(fun.name)
    )
    tempo <- ! sapply(lapply(tempo.class, FUN = "%in%", basic.class), FUN = all)
    if(any(tempo)){
        tempo.cat1 <- tempo.arg.base[tempo]
        tempo.cat2 <- sapply(tempo.class[tempo], FUN = paste0, collapse = " ")
        tempo.sep <- sapply(mapply(" ", max(nchar(tempo.cat1)) - nchar(tempo.cat1) + 3, FUN = rep, SIMPLIFY = FALSE), FUN = paste0, collapse = "")
        tempo.cat <- paste0("ERROR IN fun_check()", ifelse(is.null(fun.name), "", paste0(" INSIDE ", fun.name)), ": ANY ARGUMENT EXCEPT data MUST HAVE A BASIC CLASS\nPROBLEMATIC ARGUMENT", ifelse(base::length(tempo.cat1) > 1, "S", ""), " AND ASSOCIATED CLASS", ifelse(base::length(tempo.cat1) > 1, "ES ARE", " IS"), ":\n", paste0(tempo.cat1, tempo.sep, tempo.cat2, collapse = "\n")) # normally no NA with is.na()
        stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
    }
    # end management of special classes
    # management of NA arguments
    if(any(is.na(data.name)) | any(is.na(class)) | any(is.na(typeof)) | any(is.na(mode)) | any(is.na(length)) | any(is.na(prop)) | any(is.na(double.as.integer.allowed)) | any(is.na(all.options.in.data)) | any(is.na(na.contain)) | any(is.na(neg.values)) | any(is.na(print)) | any(is.na(fun.name))){ # normally no NA with is.na()
        tempo <- c("data.name", "class", "typeof", "mode", "length", "prop", "double.as.integer.allowed", "all.options.in.data", "na.contain", "neg.values", "print", "fun.name")[c(any(is.na(data.name)), any(is.na(class)), any(is.na(typeof)), any(is.na(mode)), any(is.na(length)), any(is.na(prop)), any(is.na(double.as.integer.allowed)), any(is.na(all.options.in.data)), any(is.na(na.contain)), any(is.na(neg.values)), any(is.na(print)), any(is.na(fun.name)))]
        tempo.cat <- paste0("ERROR IN fun_check()", ifelse(is.null(fun.name), "", paste0(" INSIDE ", fun.name)), ": NO ARGUMENT EXCEPT data AND options CAN HAVE NA VALUES\nPROBLEMATIC ARGUMENT", ifelse(length(tempo) > 1, "S ARE", " IS"), ":\n", paste(tempo, collapse = "\n")) # normally no NA with is.na()
        stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
    }
    # end management of NA arguments
    # management of NULL arguments
    tempo.arg <-c(
        "prop", 
        "double.as.integer.allowed", 
        "all.options.in.data", 
        "na.contain",
        "neg.values",
        "print"
    )
    tempo.log <- sapply(lapply(tempo.arg, FUN = get, env = sys.nframe(), inherit = FALSE), FUN = is.null)
    if(any(tempo.log) == TRUE){ # normally no NA with is.null()
        tempo.cat <- paste0("ERROR IN fun.check():\n", ifelse(sum(tempo.log, na.rm = TRUE) > 1, "THESE ARGUMENTS", "THIS ARGUMENT"), " CANNOT BE NULL:\n", paste0(tempo.arg[tempo.log], collapse = "\n"))
        stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
    }
    # end management of NULL arguments
    # dealing with logical
    # tested below
    # end dealing with logical
    # code that protects set.seed() in the global environment
    # end code that protects set.seed() in the global environment
    # warning initiation
    # end warning initiation
    # other checkings
    if( ! is.null(data.name)){
        if( ! (base::length(data.name) == 1L & all(base::class(data.name) == "character"))){ # all() without na.rm -> ok because class(NA) is "logical"
            tempo.cat <- paste0("ERROR IN fun_check()", ifelse(is.null(fun.name), "", paste0(" INSIDE ", fun.name)), ": data.name ARGUMENT MUST BE A SINGLE CHARACTER ELEMENT AND NOT ", paste(data.name, collapse = " "))
            stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
        }
    }
    if(is.null(options) & is.null(class) & is.null(typeof) & is.null(mode) &  prop == FALSE & is.null(length)){
        tempo.cat <- paste0("ERROR IN fun_check()", ifelse(is.null(fun.name), "", paste0(" INSIDE ", fun.name)), ": AT LEAST ONE OF THE options, class, typeof, mode, prop, OR length ARGUMENT MUST BE SPECIFIED (I.E, TRUE FOR prop)")
        stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
    }
    if( ! is.null(options) & ( ! is.null(class) | ! is.null(typeof) | ! is.null(mode) | prop == TRUE)){
        tempo.cat <- paste0("ERROR IN fun_check()", ifelse(is.null(fun.name), "", paste0(" INSIDE ", fun.name)), ": THE class, typeof, mode ARGUMENTS MUST BE NULL, AND prop FALSE, IF THE options ARGUMENT IS SPECIFIED\nTHE options ARGUMENT MUST BE NULL IF THE class AND/OR typeof AND/OR mode AND/OR prop ARGUMENT IS SPECIFIED")
        stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
    }
    if( ! (all(base::class(neg.values) == "logical") & base::length(neg.values) == 1L)){ # all() without na.rm -> ok because class(NA) is "logical" 
        tempo.cat <- paste0("ERROR IN fun_check()", ifelse(is.null(fun.name), "", paste0(" INSIDE ", fun.name)), ": THE neg.values ARGUMENT MUST BE TRUE OR FALSE ONLY")
        stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
    }
    if(neg.values == FALSE & is.null(class) & is.null(typeof) & is.null(mode)){
        tempo.cat <- paste0("ERROR IN fun_check()", ifelse(is.null(fun.name), "", paste0(" INSIDE ", fun.name)), ": THE neg.values ARGUMENT CANNOT BE SWITCHED TO FALSE IF class, typeof AND mode ARGUMENTS ARE NULL")
        stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
    }
    if( ! is.null(class)){ # may add "formula" and "Date" as in https://renenyffenegger.ch/notes/development/languages/R/functions/class
        if( ! all(class %in% c("vector", "logical", "integer", "numeric", "complex", "character", "matrix", "array", "data.frame", "list", "factor", "table", "expression", "name", "symbol", "function", "uneval", "environment", "ggplot2", "ggplot_built", "call") & base::length(class) == 1L)){ # length == 1L here because of class(matrix()) since R4.0.0  # all() without na.rm -> ok because class cannot be NA (tested above)
            tempo.cat <- paste0("ERROR IN fun_check()", ifelse(is.null(fun.name), "", paste0(" INSIDE ", fun.name)), ": class ARGUMENT MUST BE ONE OF THESE VALUE:\n\"vector\", \"logical\", \"integer\", \"numeric\", \"complex\", \"character\", \"matrix\", \"array\", \"data.frame\", \"list\", \"factor\", \"table\", \"expression\", \"name\", \"symbol\", \"function\", \"environment\", \"ggplot2\", \"ggplot_built\", \"call\"")
            stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
        }
        if(neg.values == FALSE & ! any(class %in% c("vector", "numeric", "integer", "matrix", "array", "data.frame", "table"))){ # no need of na.rm = TRUE for any() because %in% does not output NA
            tempo.cat <- paste0("ERROR IN fun_check()", ifelse(is.null(fun.name), "", paste0(" INSIDE ", fun.name)), ": class ARGUMENT CANNOT BE OTHER THAN \"vector\", \"numeric\", \"integer\", \"matrix\", \"array\", \"data.frame\", \"table\" IF neg.values ARGUMENT IS SWITCHED TO FALSE")
            stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
        }
    }
    if( ! is.null(typeof)){ # all the types are here: https://renenyffenegger.ch/notes/development/languages/R/functions/typeof
        if( ! (all(typeof %in% c("logical", "integer", "double", "complex", "character", "list", "expression", "symbol", "closure", "special", "builtin", "environment", "S4", "language")) & base::length(typeof) == 1L)){ # "language" is the type of object of class "call" # all() without na.rm -> ok because typeof cannot be NA (tested above)
            tempo.cat <- paste0("ERROR IN fun_check()", ifelse(is.null(fun.name), "", paste0(" INSIDE ", fun.name)), ": typeof ARGUMENT MUST BE ONE OF THESE VALUE:\n\"logical\", \"integer\", \"double\", \"complex\", \"character\", \"list\", \"expression\", \"name\", \"symbol\", \"closure\", \"special\", \"builtin\", \"environment\", \"S4\", \"language\"")
            stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
        }
        if(neg.values == FALSE & ! typeof %in% c("double", "integer")){
            tempo.cat <- paste0("ERROR IN fun_check()", ifelse(is.null(fun.name), "", paste0(" INSIDE ", fun.name)), ": typeof ARGUMENT CANNOT BE OTHER THAN \"double\" OR \"integer\" IF neg.values ARGUMENT IS SWITCHED TO FALSE")
            stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
        }
    }
    if( ! is.null(mode)){ # all the types are here: https://renenyffenegger.ch/notes/development/languages/R/functions/typeof
        if( ! (all(mode %in% c("logical", "numeric", "complex", "character", "list", "expression", "name", "symbol", "function", "environment", "S4", "call")) & base::length(mode) == 1L)){ # all() without na.rm -> ok because mode cannot be NA (tested above)
            tempo.cat <- paste0("ERROR IN fun_check()", ifelse(is.null(fun.name), "", paste0(" INSIDE ", fun.name)), ": mode ARGUMENT MUST BE ONE OF THESE VALUE:\n\"logical\", \"numeric\", \"complex\", \"character\", \"list\", \"expression\", \"name\", \"symbol\", \"function\", \"environment\", \"S4\", \"call\"")
            stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
        }
        if(neg.values == FALSE & mode != "numeric"){
            tempo.cat <- paste0("ERROR IN fun_check()", ifelse(is.null(fun.name), "", paste0(" INSIDE ", fun.name)), ": mode ARGUMENT CANNOT BE OTHER THAN \"numeric\" IF neg.values ARGUMENT IS SWITCHED TO FALSE")
            stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
        }
    }
    if( ! is.null(length)){
        if( ! (is.numeric(length) & base::length(length) == 1L & ! grepl(length, pattern = "\\."))){
            tempo.cat <- paste0("ERROR IN fun_check()", ifelse(is.null(fun.name), "", paste0(" INSIDE ", fun.name)), ": length ARGUMENT MUST BE A SINGLE INTEGER VALUE")
            stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
        }
    }
    if( ! (is.logical(prop) & base::length(prop) == 1L)){ # is.na() already checked for prop
        tempo.cat <- paste0("ERROR IN fun_check()", ifelse(is.null(fun.name), "", paste0(" INSIDE ", fun.name)), ": prop ARGUMENT MUST BE TRUE OR FALSE ONLY")
        stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
    }else if(prop == TRUE){
        if( ! is.null(class)){
            if( ! any(class %in% c("vector", "numeric", "matrix", "array", "data.frame", "table"))){ # no need of na.rm = TRUE for any() because %in% does not output NA
                tempo.cat <- paste0("ERROR IN fun_check()", ifelse(is.null(fun.name), "", paste0(" INSIDE ", fun.name)), ": class ARGUMENT CANNOT BE OTHER THAN NULL, \"vector\", \"numeric\", \"matrix\", \"array\", \"data.frame\", \"table\" IF prop ARGUMENT IS TRUE") # not integer because prop
                stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
            }
        }
        if( ! is.null(mode)){
            if(mode != "numeric"){
                tempo.cat <- paste0("ERROR IN fun_check()", ifelse(is.null(fun.name), "", paste0(" INSIDE ", fun.name)), ": mode ARGUMENT CANNOT BE OTHER THAN NULL OR \"numeric\" IF prop ARGUMENT IS TRUE")
                stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
            }
        }
        if( ! is.null(typeof)){
            if(typeof != "double"){
                tempo.cat <- paste0("ERROR IN fun_check()", ifelse(is.null(fun.name), "", paste0(" INSIDE ", fun.name)), ": typeof ARGUMENT CANNOT BE OTHER THAN NULL OR \"double\" IF prop ARGUMENT IS TRUE")
                stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
            }
        }
    }
    if( ! (all(base::class(double.as.integer.allowed) == "logical") & base::length(double.as.integer.allowed) == 1L)){ # all() without na.rm -> ok because class() never returns NA
        tempo.cat <- paste0("ERROR IN fun_check()", ifelse(is.null(fun.name), "", paste0(" INSIDE ", fun.name)), ": THE double.as.integer.allowed ARGUMENT MUST BE TRUE OR FALSE ONLY: ", paste(double.as.integer.allowed, collapse = " "))
        stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
    }
    if( ! (is.logical(all.options.in.data) & base::length(all.options.in.data) == 1L)){
        tempo.cat <- paste0("ERROR IN fun_check()", ifelse(is.null(fun.name), "", paste0(" INSIDE ", fun.name)), ": all.options.in.data ARGUMENT MUST BE A SINGLE LOGICAL VALUE (TRUE OR FALSE ONLY): ", paste(all.options.in.data, collapse = " "))
        stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
    }
    if( ! (all(base::class(na.contain) == "logical") & base::length(na.contain) == 1L)){ # all() without na.rm -> ok because class() never returns NA
        tempo.cat <- paste0("ERROR IN fun_check(): THE na.contain ARGUMENT MUST BE TRUE OR FALSE ONLY: ", paste(na.contain, collapse = " "))
        stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
    }
    if( ! (all(base::class(print) == "logical") & base::length(print) == 1L)){ # all() without na.rm -> ok because class() never returns NA
        tempo.cat <- paste0("ERROR IN fun_check(): THE print ARGUMENT MUST BE TRUE OR FALSE ONLY: ", paste(print, collapse = " "))
        stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
    }
    # data.name and fun.name tested at the beginning
    # end other checkings
    # end second round of checking and data preparation
    # package checking
    # end package checking
    # main code
    if(is.null(data.name)){
        data.name <- deparse(substitute(data))
    }
    problem <- FALSE
    text <- paste0(ifelse(is.null(fun.name), "", paste0("IN ", fun.name, ": ")), "NO PROBLEM DETECTED FOR THE ", data.name, " OBJECT")
    if(( ! is.null(options)) & (all(base::typeof(data) == "character") | all(base::typeof(data) == "integer") | all(base::typeof(data) == "double"))){ # all() without na.rm -> ok because typeof() never returns NA
        if(all(base::typeof(data) == "double")){
            if( ! all(data %% 1 == 0L, na.rm = TRUE)){
                problem <- TRUE
                text <- paste0(ifelse(is.null(fun.name), "ERROR", paste0("ERROR IN ", fun.name)), ": THE ", data.name, " OBJECT MUST BE SOME OF THESE OPTIONS: ", paste(options, collapse = " "), "\nBUT IS NOT EVEN TYPE CHARACTER OR INTEGER")
            }
        }else{
            text <- ""
            if( ! all(data %in% options)){ # no need of na.rm = TRUE for all() because %in% does not output NA
                problem <- TRUE
                text <- paste0(ifelse(is.null(fun.name), "ERROR", paste0("ERROR IN ", fun.name)), ": THE ", data.name, " OBJECT MUST BE SOME OF THESE OPTIONS: ", paste(options, collapse = " "), "\nTHE PROBLEMATIC ELEMENTS OF ", data.name, " ARE: ", paste(unique(data[ ! (data %in% options)]), collapse = " "))
            }
            if(all.options.in.data == TRUE){
                if( ! all(options %in% data)){ # no need of na.rm = TRUE for all() because %in% does not output NA
                    problem <- TRUE
                    text <- paste0(ifelse(text == "", "", paste0(text, "\n")), ifelse(is.null(fun.name), "ERROR", paste0("ERROR IN ", fun.name)), ": THE ", data.name, " OBJECT MUST BE MADE OF ALL THESE OPTIONS: ", paste(options, collapse = " "), "\nTHE MISSING ELEMENTS OF THE options ARGUMENT ARE: ",  paste(unique(options[ ! (options %in% data)]), collapse = " "))
                }
            }
            if( ! is.null(length)){
                if(base::length(data) != length){
                    problem <- TRUE
                    text <- paste0(ifelse(text == "", "", paste0(text, "\n")), ifelse(is.null(fun.name), "ERROR", paste0("ERROR IN ", fun.name)), ": THE LENGTH OF ", data.name, " MUST BE ", length, " AND NOT ", base::length(data))
                }
            }
            if(text == ""){
                text <- paste0(ifelse(is.null(fun.name), "", paste0("IN ", fun.name, ": ")), "NO PROBLEM DETECTED FOR THE ", data.name, " OBJECT")
            }
        }
    }else if( ! is.null(options)){
        problem <- TRUE
        text <- paste0(ifelse(is.null(fun.name), "ERROR", paste0("ERROR IN ", fun.name)), ": THE ", data.name, " OBJECT MUST BE SOME OF THESE OPTIONS: ", paste(options, collapse = " "), "\nBUT IS NOT EVEN TYPE CHARACTER OR INTEGER")
    }
    arg.names <- c("class", "typeof", "mode", "length")
    if( ! is.null(class)){
        if(class == "matrix"){ # because of class(matric()) since R4.0.0
            class <- c("matrix", "array")
        }else if(class == "factor" & all(base::class(data) %in% c("factor", "ordered"))){ # to deal with ordered factors # all() without na.rm -> ok because class(NA) is "logical"
            class <- c("factor", "ordered")
        }
    }
    if(is.null(options)){
        for(i2 in 1:base::length(arg.names)){
            if( ! is.null(get(arg.names[i2], env = sys.nframe(), inherit = FALSE))){
                # script to execute
                tempo.script <- '
Gael  MILLOT's avatar
Gael MILLOT committed
516
problem <- TRUE ;
517
518
if(identical(text, paste0(ifelse(is.null(fun.name), "", paste0("IN ", fun.name, ": ")), "NO PROBLEM DETECTED FOR THE ", data.name, " OBJECT"))){
text <- paste0(ifelse(is.null(fun.name), "ERROR", paste0("ERROR IN ", fun.name)), ": THE ", data.name, " OBJECT MUST BE ") ;
Gael  MILLOT's avatar
Gael MILLOT committed
519
}else{
Gael  MILLOT's avatar
Gael MILLOT committed
520
text <- paste0(text, " AND ") ; 
Gael  MILLOT's avatar
Gael MILLOT committed
521
}
522
text <- paste0(text, toupper(arg.names[i2]), " ", if(all(get(arg.names[i2], env = sys.nframe(), inherit = FALSE) %in% c("matrix", "array"))){"matrix"}else if(all(get(arg.names[i2], env = sys.nframe(), inherit = FALSE) %in% c("factor", "ordered"))){"factor"}else{get(arg.names[i2], env = sys.nframe(), inherit = FALSE)})
523
' # no need of na.rm = TRUE for all() because %in% does not output NA
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
            # end script to execute
            if(base::typeof(data) == "double" & double.as.integer.allowed == TRUE & ((arg.names[i2] == "class" & all(get(arg.names[i2], env = sys.nframe(), inherit = FALSE) == "integer")) | (arg.names[i2] == "typeof" & all(get(arg.names[i2], env = sys.nframe(), inherit = FALSE) == "integer")))){ # no need of na.rm = TRUE for all() because == does not output NA if no NA in left of ==, which is the case for arg.names # typeof(data) == "double" means no factor allowed
                if( ! all(data %% 1 == 0L, na.rm = TRUE)){ # to check integers (use %%, meaning the remaining of a division): see the precedent line. isTRUE(all.equal(data%%1, rep(0, length(data)))) not used because we strictly need zero as a result. Warning: na.rm = TRUE required here for all()
                    eval(parse(text = tempo.script)) # execute tempo.script
                }
            }else if( ! any(all(get(arg.names[i2], env = sys.nframe(), inherit = FALSE) %in% c("vector", "ggplot2"))) & ! all(eval(parse(text = paste0(arg.names[i2], "(data)"))) %in% get(arg.names[i2], env = sys.nframe(), inherit = FALSE))){ # test the four c("class", "typeof", "mode", "length") arguments with their corresponding function. No need of na.rm = TRUE for all() because %in% does not output NA # no need of na.rm = TRUE for all() because %in% does not output NA # no need of na.rm = TRUE for any() because get get(arg.names) does not contain NA
                eval(parse(text = tempo.script)) # execute tempo.script
            }else if(arg.names[i2] == "class" & all(get(arg.names[i2], env = sys.nframe(), inherit = FALSE) == "vector") & ! (all(base::class(data) %in% "numeric") | all(base::class(data) %in% "integer") | all(base::class(data) %in% "character") | all(base::class(data) %in% "logical"))){ # test class == "vector". No need of na.rm = TRUE for all() because %in% does not output NA # no need of na.rm = TRUE for all() because == does not output NA if no NA in left of ==, which is the case for arg.names
                eval(parse(text = tempo.script)) # execute tempo.script
            }else if(arg.names[i2] == "class" & all(get(arg.names[i2], env = sys.nframe(), inherit = FALSE) == "ggplot2") & ! all(base::class(data) %in% c("gg", "ggplot"))){ # test ggplot object # no need of na.rm = TRUE for all() because == does not output NA if no NA in left of ==, which is the case for arg.names # no need of na.rm = TRUE for all() because %in% does not output NA
                eval(parse(text = tempo.script)) # execute tempo.script
            }
            }
        }
    }
539
if(prop == TRUE & all(base::typeof(data) == "double")){ # all() without na.rm -> ok because typeof(NA) is "logical"
540
541
542
543
544
545
546
547
548
    if(is.null(data) | any(data < 0 | data > 1, na.rm = TRUE)){ # works if data is NULL # Warning: na.rm = TRUE required here for any() # typeof(data) == "double" means no factor allowed
        problem <- TRUE
        if(identical(text, paste0(ifelse(is.null(fun.name), "", paste0("IN ", fun.name, ": ")), "NO PROBLEM DETECTED FOR THE ", data.name, " OBJECT"))){
            text <- paste0(ifelse(is.null(fun.name), "ERROR", paste0("ERROR IN ", fun.name)), ": ")
        }else{
            text <- paste0(text, " AND ")
        }
        text <- paste0(text, "THE ", data.name, " OBJECT MUST BE DECIMAL VALUES BETWEEN 0 AND 1")
    }
549
}else if(prop == TRUE){
550
551
552
553
554
555
556
    problem <- TRUE
    if(identical(text, paste0(ifelse(is.null(fun.name), "", paste0("IN ", fun.name, ": ")), "NO PROBLEM DETECTED FOR THE ", data.name, " OBJECT"))){
        text <- paste0(ifelse(is.null(fun.name), "ERROR", paste0("ERROR IN ", fun.name)), ": ")
    }else{
        text <- paste0(text, " AND ")
    }
    text <- paste0(text, "THE ", data.name, " OBJECT MUST BE DECIMAL VALUES BETWEEN 0 AND 1")
557
}
558
if(all(base::class(data) %in% "expression")){ # no need of na.rm = TRUE for all() because %in% does not output NA
559
    data <- as.character(data) # to evaluate the presence of NA
Gael  MILLOT's avatar
Gael MILLOT committed
560
}
561
if(na.contain == FALSE & (base::mode(data) %in% c("logical", "numeric", "complex", "character", "list"))){ # before it was ! (class(data) %in% c("function", "environment"))
562
563
564
565
566
567
568
569
570
    if(any(is.na(data)) == TRUE){ # not on the same line because when data is class envir or function , do not like that # normally no NA with is.na()
        problem <- TRUE
        if(identical(text, paste0(ifelse(is.null(fun.name), "", paste0("IN ", fun.name, ": ")), "NO PROBLEM DETECTED FOR THE ", data.name, " OBJECT"))){
            text <- paste0(ifelse(is.null(fun.name), "ERROR", paste0("ERROR IN ", fun.name)), ": ")
        }else{
            text <- paste0(text, " AND ")
        }
        text <- paste0(text, "THE ", data.name, " OBJECT CONTAINS NA WHILE NOT AUTHORIZED")
    }
Gael  MILLOT's avatar
Gael MILLOT committed
571
}
572
if(neg.values == FALSE & all(base::mode(data) %in% "numeric") & ! any(base::class(data) %in% "factor")){ # no need of na.rm = TRUE for all() because %in% does not output NA
573
574
575
576
577
578
579
580
581
    if(any(data < 0, na.rm = TRUE)){ # Warning: na.rm = TRUE required here for any()
        problem <- TRUE
        if(identical(text, paste0(ifelse(is.null(fun.name), "", paste0("IN ", fun.name, ": ")), "NO PROBLEM DETECTED FOR THE ", data.name, " OBJECT"))){
            text <- paste0(ifelse(is.null(fun.name), "ERROR", paste0("ERROR IN ", fun.name)), ": ")
        }else{
            text <- paste0(text, " AND ")
        }
        text <- paste0(text, "THE ", data.name, " OBJECT MUST BE MADE OF NON NEGATIVE NUMERIC VALUES")
    }
582
}else if(neg.values == FALSE){
583
584
585
586
587
588
589
    problem <- TRUE
    if(identical(text, paste0(ifelse(is.null(fun.name), "", paste0("IN ", fun.name, ": ")), "NO PROBLEM DETECTED FOR THE ", data.name, " OBJECT"))){
        text <- paste0(ifelse(is.null(fun.name), "ERROR", paste0("ERROR IN ", fun.name)), ": ")
    }else{
        text <- paste0(text, " AND ")
    }
    text <- paste0(text, "THE ", data.name, " OBJECT MUST BE MADE OF NON NEGATIVE VALUES BUT IS ", ifelse(any(base::class(data) %in% "factor"), "A FACTOR", "NOT EVEN MODE NUMERIC"))
Gael  MILLOT's avatar
Gael MILLOT committed
590
}
Gael  MILLOT's avatar
Gael MILLOT committed
591
if(print == TRUE & problem == TRUE){
592
    cat(paste0("\n\n================\n\n", text, "\n\n================\n\n"))
Gael  MILLOT's avatar
Gael MILLOT committed
593
}
594
595
# output
output <- list(problem = problem, text = text, object.name = data.name)
Gael  MILLOT's avatar
Gael MILLOT committed
596
return(output)
597
598
# end output
# end main code
Gael  MILLOT's avatar
Gael MILLOT committed
599
}
Gael  MILLOT's avatar
Gael MILLOT committed
600

601
######## fun_secu() #### verif that local variables are not present in other envs
Gael  MILLOT's avatar
Gael MILLOT committed
602
603
604


fun_secu <- function(pos = 1, name = NULL){
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
    # AIM
    # Verify that variables in the environment defined by the pos parameter are not present in the above environment (following R Scope). This can be used to avoid R scope preference of functions like get()
    # ARGUMENTS
    # pos: single integer indicating the position of the environment checked (argument n of parent.frame()). Value 1 means one step above the fun_secu() local environment (by default). This means that when fun_secu(pos = 1) is used inside a function A, it checks if variables in the local environment of this function A are also present in above environments (following R Scope). When fun_secu(pos = 1) is used in the Global environment, it checks the objects of this environment
    # name: single character string indicating the name of the function checked. If NULL, fun_secu() checks all the variables of the environment indicated by pos, as explained in the pos argument description. If non-null, fun_secu() checks all the variables presents in the local env of the function will be checked in the above envs (which includes the working environment (Global env)
    # RETURN
    # A character string of the local variables that match variables in the different environments of the R scope, or NULL if no match
    # REQUIRED PACKAGES
    # None
    # REQUIRED FUNCTIONS FROM CUTE_LITTLE_R_FUNCTION
    # fun_check()
    # EXAMPLES
    # fun_secu()
    # fun_secu(pos = 2)
    # mean <- 0 ; fun1 <- function(){sd <- 1 ; fun_secu(name = as.character(sys.calls()[[length(sys.calls())]]))} ; fun2 <- function(){cor <- 2 ; fun1()} ; fun1() ; fun2() ; rm(mean) # sys.calls() gives the function name at top stack of the imbricated functions, sys.calls()[[length(sys.calls())]] the name of the just above function. This can also been used for the above function: as.character(sys.call(1))
    # test.pos <- 2 ; mean <- 0 ; fun1 <- function(){sd <- 1 ; fun_secu(pos = test.pos, name = if(length(sys.calls()) >= test.pos){as.character(sys.calls()[[length(sys.calls()) + 1 - test.pos]])}else{search()[ (1:length(search()))[test.pos - length(sys.calls())]]})} ; fun2 <- function(){cor <- 2 ; fun1()} ; fun1() ; fun2() ; rm(mean) # for argument name, here is a way to have the name of the tested environment according to test.pos value
    # DEBUGGING
    # pos = 1 ; name = NULL # for function debugging
    # function name
    function.name <- paste0(as.list(match.call(expand.dots = FALSE))[[1]], "()")
    arg.user.setting <- as.list(match.call(expand.dots = FALSE))[-1] # list of the argument settings (excluding default values not provided by the user)
    # end function name
    # required function checking
    if(length(utils::find("fun_check", mode = "function")) == 0L){
        tempo.cat <- paste0("ERROR IN ", function.name, "\nREQUIRED fun_check() FUNCTION IS MISSING IN THE R ENVIRONMENT")
        stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
    }
    # end required function checking
    # argument primary checking
    # arg with no default values
    # end arg with no default values
    # using fun_check()
    arg.check <- NULL #
    text.check <- NULL #
    checked.arg.names <- NULL # for function debbuging: used by r_debugging_tools
    ee <- expression(arg.check <- c(arg.check, tempo$problem) , text.check <- c(text.check, tempo$text) , checked.arg.names <- c(checked.arg.names, tempo$object.name))
    tempo <- fun_check(data = pos, class = "vector", typeof = "integer", double.as.integer.allowed = TRUE, length = 1, fun.name = function.name) ; eval(ee)
    if( ! is.null(name)){
        tempo <- fun_check(data = name, class = "vector", typeof = "character", length = 1, fun.name = function.name) ; eval(ee)
    }
    if(any(arg.check) == TRUE){
        stop(paste0("\n\n================\n\n", paste(text.check[arg.check], collapse = "\n"), "\n\n================\n\n"), call. = FALSE) #
    }
    # end using fun_check()
    # source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.7/r_debugging_tools-v1.7.R") ; eval(parse(text = str_basic_arg_check_dev)) ; eval(parse(text = str_arg_check_with_fun_check_dev)) # activate this line and use the function (with no arguments left as NULL) to check arguments status and if they have been checked using fun_check()
    # end argument primary checking
    # second round of checking and data preparation
    # management of NA arguments
    tempo.arg <- names(arg.user.setting) # values provided by the user
    tempo.log <- suppressWarnings(sapply(lapply(lapply(tempo.arg, FUN = get, env = sys.nframe(), inherit = FALSE), FUN = is.na), FUN = any)) & lapply(lapply(tempo.arg, FUN = get, env = sys.nframe(), inherit = FALSE), FUN = length) == 1L # no argument provided by the user can be just NA
    if(any(tempo.log) == TRUE){
        tempo.cat <- paste0("ERROR IN ", function.name, "\n", ifelse(sum(tempo.log, na.rm = TRUE) > 1, "THESE ARGUMENTS", "THIS ARGUMENT"), " CANNOT JUST BE NA:", paste0(tempo.arg[tempo.log], collapse = "\n"))
        stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
    }
    # end management of NA arguments
    # management of NULL arguments
    tempo.arg <- c(
        "pos"
    )
    tempo.log <- sapply(lapply(tempo.arg, FUN = get, env = sys.nframe(), inherit = FALSE), FUN = is.null)
    if(any(tempo.log) == TRUE){
        tempo.cat <- paste0("ERROR IN ", function.name, "\n", ifelse(sum(tempo.log, na.rm = TRUE) > 1, "THESE ARGUMENTS", "THIS ARGUMENT"), " CANNOT BE NULL:", paste0(tempo.arg[tempo.log], collapse = "\n"))
        stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
    }
    # end management of NULL arguments
    # end second round of checking and data preparation
    # main code
    # match.list <- vector("list", length = (length(sys.calls()) - 1 + length(search()) + ifelse(length(sys.calls()) == 1L, -1, 0))) # match.list is a list of all the environment tested (local of functions and R envs), length(sys.calls()) - 1 to remove the level of the fun_secu() function, sys.calls() giving all the names of the imbricated functions, including fun_secu, ifelse(length(sys.calls()) == 1L, -1, 0) to remove Global env if this one is tested
    tempo.name <- rev(as.character(unlist(sys.calls()))) # get names of frames (i.e., enclosed env)
    tempo.frame <- rev(sys.frames())  # get frames (i.e., enclosed env)
    # dealing with source()
    # source() used in the Global env creates three frames above the Global env, which should be removed because not very interesting for variable duplications. Add a <<-(sys.frames()) in this code and source anova_contrasts code to see this. With ls(a[[4]]), we can see the content of each env, which are probably elements of source()
    if(any(sapply(tempo.frame, FUN = environmentName) %in% "R_GlobalEnv")){
        global.pos <- which(sapply(tempo.frame, FUN = environmentName) %in% "R_GlobalEnv")
        # remove the global env (because already in search(), and all the oabove env
        tempo.name <- tempo.name[-c(global.pos:length(tempo.frame))]
        tempo.frame <- tempo.frame[-c(global.pos:length(tempo.frame))]
    }
    # end dealing with source()
    # might have a problem if(length(tempo.name) == 0L){
    match.list <- vector("list", length = length(tempo.name) + length(search())) # match.list is a list of all the environment tested (local of functions and R envs), length(sys.calls()) - 1 to remove the level of the fun_secu() function, sys.calls() giving all the names of the imbricated functions, including fun_secu, ifelse(length(sys.calls()) == 1L, -1, 0) to remove Global env if this one is tested
    ls.names <- c(tempo.name, search()) # names of the functions + names of the search() environments
    ls.input <- c(tempo.frame, as.list(search())) # environements of the functions + names of the search() environments
    names(match.list) <- ls.names # 
    match.list <- match.list[-c(1:(pos + 1))] # because we check only above pos
    ls.tested <- ls.input[[pos + 1]]
    ls.input <- ls.input[-c(1:(pos + 1))]
    for(i1 in 1:length(match.list)){
        if(any(ls(name = ls.input[[i1]], all.names = TRUE) %in% ls(name = ls.tested, all.names = TRUE))){
            match.list[i1] <- list(ls(name = ls.input[[i1]], all.names = TRUE)[ls(name = ls.input[[i1]], all.names = TRUE) %in% ls(name = ls.tested, all.names = TRUE)])
        }
    }
    if( ! all(sapply(match.list, FUN = is.null))){
        output <- paste0("SOME VARIABLES ", ifelse(is.null(name), "OF THE CHECKED ENVIRONMENT", paste0("OF ", name)), " ARE ALSO PRESENT IN :\n", paste0(names(match.list[ ! sapply(match.list, FUN = is.null)]), ": ", sapply(match.list[ ! sapply(match.list, FUN = is.null)], FUN = paste0, collapse = " "), collapse = "\n"))
    }else{
        output <- NULL
    }
    return(output)
Gael  MILLOT's avatar
Gael MILLOT committed
703
704
705
}


706
######## fun_info() #### broad description of an object
Gael  MILLOT's avatar
Gael MILLOT committed
707
708


709
710
# todo list check OK
# Check r_debugging_tools-v1.4.R OK
711
712
713
714
# Check fun_test() (see cute_checks.docx) OK
# example sheet OK 
# check all and any OK
# -> clear to go Apollo
715
fun_info <- function(
716
717
718
    data, 
    n = NULL, 
    warn.print = TRUE
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
    # AIM
    # Provide a broad description of an object
    # WARNINGS
    # None
    # ARGUMENTS
    # data: object to analyse
    # n: positive integer value indicating the n first number of elements to display per compartment of the output list (i.e., head(..., n)). Write NULL to return all the elements. Does not apply for the $STRUCTURE compartment output
    # warn.print: logical. Print potential warnings at the end of the execution? If FALSE the warning messages are added in the output list as an additional compartment (or NULL if no message).
    # RETURN
    # A list containing information, depending on the class and type of data. The backbone is generally:
    # $NAME: name of the object
    # $CLASS: class of the object (class() value)
    # $TYPE: type of the object (typeof() value)
    # $LENGTH: length of the object (length() value)
    # $NA.NB: number of NA and NaN (only for type "logical", "integer", "double", "complex", "character" or "list")
    # $HEAD: head of the object (head() value)
    # $TAIL: tail of the object (tail() value)
    # $DIMENSION: dimension (only for object with dimensions)
    # $SUMMARY: object summary (summary() value)
    # $STRUCTURE: object structure (str() value)
    # $WARNING: warning messages (only if the warn.print argument is FALSE)
    # If data is made of numerics, provide also:
    # $INF.NB: number of Inf and -Inf
    # $RANGE: range after removing Inf and NA
    # $SUM: sum after removing Inf and NA
    # $MEAN: mean after removing Inf and NA
    # If data is a 2D object, provide also:
    # $ROW_NAMES: row names
    # $COL_NAMES: column names
    # If data is a data frame, provide also:
    # $COLUMN_TYPE: type of each column (typeof() value)
    # If data is a list, provide also:
    # $COMPARTMENT_NAMES: names of the comprtments
    # $COMPARTMENT_TYPE: type of each compartment (typeof() value)
    # REQUIRED PACKAGES
    # None
    # REQUIRED FUNCTIONS FROM THE cute PACKAGE
    # fun_check()
    # fun_get_message()
    # EXAMPLE
    # fun_info(data = 1:3)
    # see http
    # DEBUGGING
    # mat1 <- matrix(1:3) ; data = env1 ; n = NULL ; warn.print = TRUE # for function debugging
    # function name
    function.name <- paste0(as.list(match.call(expand.dots = FALSE))[[1]], "()")
    arg.names <- names(formals(fun = sys.function(sys.parent(n = 2)))) # names of all the arguments
    arg.user.setting <- as.list(match.call(expand.dots = FALSE))[-1] # list of the argument settings (excluding default values not provided by the user)
    # end function name
    # required function checking
    req.function <- c(
        "fun_check", 
        "fun_get_message"
    )
    tempo <- NULL
    for(i1 in req.function){
        if(length(find(i1, mode = "function")) == 0L){
            tempo <- c(tempo, i1)
        }
    }
    if( ! is.null(tempo)){
        tempo.cat <- paste0("ERROR IN ", function.name, "\nREQUIRED cute FUNCTION", ifelse(length(tempo) > 1, "S ARE", " IS"), " MISSING IN THE R ENVIRONMENT:\n", paste0(tempo, collapse = "()\n"))
        stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
    }
    # end required function checking
    # reserved words
    # end reserved words
    # arg with no default values
    mandat.args <- c(
        "data"
    )
    tempo <- eval(parse(text = paste0("missing(", paste0(mandat.args, collapse = ") | missing("), ")")))
    if(any(tempo)){ # normally no NA for missing() output
        tempo.cat <- paste0("ERROR IN ", function.name, "\nFOLLOWING ARGUMENT", ifelse(length(mandat.args) > 1, "S HAVE", "HAS"), " NO DEFAULT VALUE AND REQUIRE ONE:\n", paste0(mandat.args, collapse = "\n"))
        stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
    }
    # end arg with no default values
    # argument primary checking
    arg.check <- NULL #
    text.check <- NULL #
    checked.arg.names <- NULL # for function debbuging: used by r_debugging_tools
    ee <- expression(arg.check <- c(arg.check, tempo$problem) , text.check <- c(text.check, tempo$text) , checked.arg.names <- c(checked.arg.names, tempo$object.name))
    if( ! is.null(n)){
        tempo <- fun_check(data = n, class = "vector", typeof = "integer", length = 1, double.as.integer.allowed = TRUE, fun.name = function.name) ; eval(ee)
    }else{
        # no fun_check test here, it is just for checked.arg.names
        tempo <- fun_check(data = n, class = "vector")
        checked.arg.names <- c(checked.arg.names, tempo$object.name)
    }
    tempo <- fun_check(data = warn.print, class = "logical", length = 1, fun.name = function.name) ; eval(ee)
    if(any(arg.check) == TRUE){ # normally no NA
        stop(paste0("\n\n================\n\n", paste(text.check[arg.check], collapse = "\n"), "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between == #
    }
    # source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.7/r_debugging_tools-v1.7.R") ; eval(parse(text = str_basic_arg_check_dev)) ; eval(parse(text = str_arg_check_with_fun_check_dev)) # activate this line and use the function (with no arguments left as NULL) to check arguments status and if they have been checked using fun_check()
    # end argument primary checking
    # second round of checking and data preparation
    # management of NA arguments
    tempo.arg <- names(arg.user.setting) # values provided by the user
    tempo.log <- suppressWarnings(sapply(lapply(lapply(tempo.arg, FUN = get, env = sys.nframe(), inherit = FALSE), FUN = is.na), FUN = any)) & lapply(lapply(tempo.arg, FUN = get, env = sys.nframe(), inherit = FALSE), FUN = length) == 1L # no argument provided by the user can be just NA
    if(any(tempo.log) == TRUE){ # normally no NA because is.na() used here
        tempo.cat <- paste0("ERROR IN ", function.name, ":\n", ifelse(sum(tempo.log, na.rm = TRUE) > 1, "THESE ARGUMENTS\n", "THIS ARGUMENT\n"), paste0(tempo.arg[tempo.log], collapse = "\n"),"\nCANNOT JUST BE NA")
        stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
    }
    # end management of NA arguments
    # management of NULL arguments
    tempo.arg <-c(
        "data", 
        # "n", # because can be NULL
        "warn.print"
    )
    tempo.log <- sapply(lapply(tempo.arg, FUN = get, env = sys.nframe(), inherit = FALSE), FUN = is.null)
    if(any(tempo.log) == TRUE){# normally no NA with is.null()
        tempo.cat <- paste0("ERROR IN ", function.name, ":\n", ifelse(sum(tempo.log, na.rm = TRUE) > 1, "THESE ARGUMENTS\n", "THIS ARGUMENT\n"), paste0(tempo.arg[tempo.log], collapse = "\n"),"\nCANNOT BE NULL")
        stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
    }
    # end management of NULL arguments
    # code that protects set.seed() in the global environment
    # end code that protects set.seed() in the global environment
    # warning initiation
    ini.warning.length <- options()$warning.length
    options(warning.length = 8170)
    warn <- NULL
    # warn.count <- 0 # not required
    # end warning initiation
    # other checkings
    if( ! is.null(n)){
        if(n < 1){
            tempo.cat <- paste0("ERROR IN ", function.name, ": n ARGUMENT MUST BE A POSITIVE AND NON NULL INTEGER")
            stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
        }else if(is.finite(n)){
            # warn.count <- warn.count + 1
            tempo.warn <- paste0("SOME COMPARTMENTS CAN BE TRUNCATED (n ARGUMENT IS ", n, ")")
            warn <- paste0(ifelse(is.null(warn), tempo.warn, paste0(warn, "\n\n", tempo.warn)))
        }
    }
    # end other checkings
    # reserved word checking
    # end reserved word checking
    # end second round of checking and data preparation
    # package checking
    # end package checking
    # main code
    # new environment
    env.name <- paste0("env", as.numeric(Sys.time()))
    if(exists(env.name, where = -1)){ # verify if still ok when fun_info() is inside a function
        tempo.cat <- paste0("ERROR IN ", function.name, ": ENVIRONMENT env.name ALREADY EXISTS. PLEASE RERUN ONCE")
        stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
    }else{
        assign(env.name, new.env())
        assign("data", data, envir = get(env.name, env = sys.nframe(), inherit = FALSE)) # data assigned in a new envir for test
    }
    # end new environment
    data.name <- deparse(substitute(data))
    output <- list("NAME" = data.name)
    tempo.try.error <- fun_get_message(data = "class(data)", kind = "error", header = FALSE, env = get(env.name, env = sys.nframe(), inherit = FALSE))
    if(is.null(tempo.try.error)){
        tempo <- list("CLASS" = class(data))
        output <- c(output, tempo)
    }
    tempo.try.error <- fun_get_message(data = "typeof(data)", kind = "error", header = FALSE, env = get(env.name, env = sys.nframe(), inherit = FALSE))
    if(is.null(tempo.try.error)){
        tempo <- list("TYPE" = typeof(data))
        output <- c(output, tempo)
    }
    tempo.try.error <- fun_get_message(data = "length(data)", kind = "error", header = FALSE, env = get(env.name, env = sys.nframe(), inherit = FALSE))
    if(is.null(tempo.try.error)){
        tempo <- list("LENGTH" = length(data))
        output <- c(output, tempo)
    }
    if(all(typeof(data) %in% c("integer", "numeric", "double")) & ! any(class(data) %in% "factor")){ # all() without na.rm -> ok because typeof(NA) is "logical" # any() without na.rm -> ok because class(NA) is "logical"
        tempo <- list("INF.NB" = sum(is.infinite(data)))
        output <- c(output, tempo)
        tempo <- list("RANGE" = range(data[ ! is.infinite(data)], na.rm = TRUE))
        output <- c(output, tempo)
        tempo <- list("SUM" = sum(data[ ! is.infinite(data)], na.rm = TRUE))
        output <- c(output, tempo)
        tempo <- list("MEAN" = mean(data[ ! is.infinite(data)], na.rm = TRUE))
        output <- c(output, tempo)
    }
    if(all(typeof(data) %in% c("logical", "integer", "double", "complex", "character", "list"))){ # all() without na.rm -> ok because typeof(NA) is "logical"
        tempo.try.error <- fun_get_message(data = "is.na(data)", kind = "error", header = FALSE, env = get(env.name, env = sys.nframe(), inherit = FALSE))
        if(is.null(tempo.try.error)){
            tempo <- list("NA.NB" = sum(is.na(data)))
            output <- c(output, tempo)
        }
    }
    tempo.try.error <- fun_get_message(data = "head(data)", kind = "error", header = FALSE, env = get(env.name, env = sys.nframe(), inherit = FALSE))
    if(is.null(tempo.try.error)){
        tempo <- list("HEAD" = head(data))
        output <- c(output, tempo)
        tempo <- list("TAIL" = tail(data)) # no reason that tail() does not work if head() works
        output <- c(output, tempo)
    }
    tempo.try.error <- fun_get_message(data = "dim(data)", kind = "error", header = FALSE, env = get(env.name, env = sys.nframe(), inherit = FALSE))
    if(is.null(tempo.try.error)){
        if(length(dim(data)) > 0){
            tempo <- list("DIMENSION" = dim(data))
            if(length(tempo[[1]]) == 2L){
                names(tempo[[1]]) <- c("NROW", "NCOL")
            }
            output <- c(output, tempo)
        }
    }
    if(all(class(data) == "data.frame") | all(class(data) %in% c("matrix", "array")) | all(class(data) == "table")){ # all() without na.rm -> ok because typeof(NA) is "logical"
        if(length(dim(data)) > 1){ # to avoid 1D table
            tempo <- list("ROW_NAMES" = dimnames(data)[[1]])
            output <- c(output, tempo)
            tempo <- list("COLUM_NAMES" = dimnames(data)[[2]])
            output <- c(output, tempo)
        }
    }
    tempo.try.error <- fun_get_message(data = "summary(data)", kind = "error", header = FALSE, env = get(env.name, env = sys.nframe(), inherit = FALSE))
    if(is.null(tempo.try.error)){
        tempo <- list("SUMMARY" = summary(data))
        output <- c(output, tempo)
    }
    tempo.try.error <- fun_get_message(data = "noquote(matrix(capture.output(str(data))))", kind = "error", header = FALSE, env = get(env.name, env = sys.nframe(), inherit = FALSE))
    if(is.null(tempo.try.error)){
        tempo <- capture.output(str(data))
        tempo <- list("STRUCTURE" = noquote(matrix(tempo, dimnames = list(rep("", length(tempo)), "")))) # str() print automatically, ls.str() not but does not give the order of the data.frame
        output <- c(output, tempo)
    }
    if(all(class(data) == "data.frame")){ # all() without na.rm -> ok because class(NA) is "logical"
        tempo <- list("COLUMN_TYPE" = sapply(data, FUN = "typeof"))
        if(any(sapply(data, FUN = "class") %in% "factor")){ # if an ordered factor is present, then sapply(data, FUN = "class") return a list but works with any(sapply(data, FUN = "class") %in% "factor") # any() without na.rm -> ok because class(NA) is "logical"
            tempo.class <- sapply(data, FUN = "class")
            if(any(unlist(tempo.class) %in% "ordered")){ # any() without na.rm -> ok because class(NA) is "logical"
                tempo2 <- sapply(tempo.class, paste, collapse = " ") # paste the "ordered" factor" in "ordered factor"
            }else{
                tempo2 <- unlist(tempo.class)
            }
            tempo[["COLUMN_TYPE"]][grepl(x = tempo2, pattern = "factor")] <- tempo2[grepl(x = tempo2, pattern = "factor")]
        }
        output <- c(output, tempo)
    }
    if(all(class(data) == "list")){ # all() without na.rm -> ok because class(NA) is "logical"
        tempo <- list("COMPARTMENT_NAMES" = names(data))
        output <- c(output, tempo)
        tempo <- list("COMPARTMENT_TYPE" = sapply(data, FUN = "typeof"))
        if(any(unlist(sapply(data, FUN = "class")) %in% "factor")){ # if an ordered factor is present, then sapply(data, FUN = "class") return a list but works with any(sapply(data, FUN = "class") %in% "factor")  # any() without na.rm -> ok because class(NA) is "logical"
            tempo.class <- sapply(data, FUN = "class")
            if(any(unlist(tempo.class) %in% "ordered")){ # any() without na.rm -> ok because class(NA) is "logical"
                tempo2 <- sapply(tempo.class, paste, collapse = " ") # paste the "ordered" factor" in "ordered factor"
            }else{
                tempo2 <- unlist(tempo.class)
            }
            tempo[["COMPARTMENT_TYPE"]][grepl(x = tempo2, pattern = "factor")] <- tempo2[grepl(x = tempo2, pattern = "factor")]
        }
        output <- c(output, tempo)
    }
    if( ! is.null(n)){
        output[names(output) != "STRUCTURE"] <- lapply(X = output[names(output) != "STRUCTURE"], FUN = head, n = n, simplify = FALSE)
    }
    # output
    if(warn.print == FALSE){
        output <- c(output, WARNING = warn)
    }else if(warn.print == TRUE & ! is.null(warn)){
        on.exit(warning(paste0("FROM ", function.name, ":\n\n", warn), call. = FALSE))
    }
    on.exit(exp = options(warning.length = ini.warning.length), add = TRUE)
    return(output)
    # end output
    # end main code
983
}
Gael's avatar
Gael committed
984
985


Gael's avatar
Gael committed
986
######## fun_head() #### head of the left or right of big 2D objects
Gael's avatar
Gael committed
987
988


Gael's avatar
Gael committed
989
fun_head <- function(
990
991
992
    data1, 
    n = 6, 
    side = "l"
Gael's avatar
Gael committed
993
){
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
    # AIM
    # as head() but display the left or right head of big 2D objects
    # ARGUMENTS
    # data1: any object but more dedicated for matrix, data frame or table
    # n: as in head() but for for matrix, data frame or table, number of dimension to print (10 means 10 rows and columns)
    # side: either "l" or "r" for the left or right side of the 2D object (only for matrix, data frame or table)
    # BEWARE: other arguments of head() not used
    # RETURN
    # the head
    # REQUIRED PACKAGES
    # none
    # REQUIRED FUNCTIONS FROM CUTE_LITTLE_R_FUNCTION
    # fun_check()
    # EXAMPLES
    # obs1 = matrix(1:30, ncol = 5, dimnames = list(letters[1:6], LETTERS[1:5])) ; obs1 ; fun_head(obs1, 3)
    # DEBUGGING
    # data1 = matrix(1:30, ncol = 5, dimnames = list(letters[1:2], LETTERS[1:5])) # for function debugging
    # function name
    function.name <- paste0(as.list(match.call(expand.dots = FALSE))[[1]], "()")
    # end function name
    # required function checking
    if(length(utils::find("fun_check", mode = "function")) == 0L){
        tempo.cat <- paste0("ERROR IN ", function.name, ": REQUIRED fun_check() FUNCTION IS MISSING IN THE R ENVIRONMENT")
        stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
    }
    # end required function checking
    # argument checking
    arg.check <- NULL #
    text.check <- NULL #
    checked.arg.names <- NULL # for function debbuging: used by r_debugging_tools
    ee <- expression(arg.check <- c(arg.check, tempo$problem) , text.check <- c(text.check, tempo$text) , checked.arg.names <- c(checked.arg.names, tempo$object.name))
    tempo <- fun_check(data = n, class = "vector", typeof = "integer", double.as.integer.allowed = TRUE, length = 1, fun.name = function.name) ; eval(ee)
    tempo <- fun_check(data = side, options = c("l", "r"), length = 1, fun.name = function.name) ; eval(ee)
    if(any(arg.check) == TRUE){
        stop(paste0("\n\n================\n\n", paste(text.check[arg.check], collapse = "\n"), "\n\n================\n\n"), call. = FALSE) #
    }
    # source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.7/r_debugging_tools-v1.7.R") ; eval(parse(text = str_basic_arg_check_dev)) ; eval(parse(text = str_arg_check_with_fun_check_dev)) # activate this line and use the function (with no arguments left as NULL) to check arguments status and if they have been checked using fun_check()
    # end argument checking
    # main code
    if( ! (any(class(data1) %in% c("data.frame", "table")) | all(class(data1) %in% c("matrix", "array")))){ # before R4.0.0, it was  ! any(class(data1) %in% c("matrix", "data.frame", "table"))
        return(head(data1, n))
    }else{
        obs.dim <- dim(data1)
        row <- 1:ifelse(obs.dim[1] < n, obs.dim[1], n)
        if(side == "l"){
            col <- 1:ifelse(obs.dim[2] < n, obs.dim[2], n)
        }
        if(side == "r"){
            col <- ifelse(obs.dim[2] < n, 1, obs.dim[2] - n + 1):obs.dim[2]
        }
        return(data1[row, col])
    }
1046
}
Gael's avatar
Gael committed
1047
1048


Gael's avatar
Gael committed
1049
######## fun_tail() #### tail of the left or right of big 2D objects
Gael's avatar
Gael committed
1050
1051


Gael's avatar
Gael committed
1052
fun_tail <- function(
1053
1054
1055
    data1, 
    n = 6, 
    side = "l"
Gael's avatar
Gael committed
1056
){
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
    # AIM
    # as tail() but display the left or right head of big 2D objects
    # ARGUMENTS
    # data1: any object but more dedicated for matrix, data frame or table
    # n: as in tail() but for for matrix, data frame or table, number of dimension to print (10 means 10 rows and columns)
    # side: either "l" or "r" for the left or right side of the 2D object (only for matrix, data frame or table)
    # BEWARE: other arguments of tail() not used
    # RETURN
    # the tail
    # REQUIRED PACKAGES
    # none
    # REQUIRED FUNCTIONS FROM CUTE_LITTLE_R_FUNCTION
    # fun_check()
    # EXAMPLES
    # obs1 = matrix(1:30, ncol = 5, dimnames = list(letters[1:6], LETTERS[1:5])) ; obs1 ; fun_tail(obs1, 3, "r")
    # DEBUGGING
    # data1 = matrix(1:10, ncol = 5, dimnames = list(letters[1:2], LETTERS[1:5])) # for function debugging
    # function name
    function.name <- paste0(as.list(match.call(expand.dots = FALSE))[[1]], "()")
    # end function name
    # required function checking
    if(length(utils::find("fun_check", mode = "function")) == 0L){
        tempo.cat <- paste0("ERROR IN ", function.name, ": REQUIRED fun_check() FUNCTION IS MISSING IN THE R ENVIRONMENT")
        stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
    }
    # end required function checking
    # argument checking
    arg.check <- NULL #
    text.check <- NULL #
    checked.arg.names <- NULL # for function debbuging: used by r_debugging_tools
    ee <- expression(arg.check <- c(arg.check, tempo$problem) , text.check <- c(text.check, tempo$text) , checked.arg.names <- c(checked.arg.names, tempo$object.name))
    tempo <- fun_check(data = n, class = "vector", typeof = "integer", double.as.integer.allowed = TRUE, length = 1, fun.name = function.name) ; eval(ee)
    tempo <- fun_check(data = side, options = c("l", "r"), length = 1, fun.name = function.name) ; eval(ee)
    if(any(arg.check) == TRUE){
        stop(paste0("\n\n================\n\n", paste(text.check[arg.check], collapse = "\n"), "\n\n================\n\n"), call. = FALSE) #
    }
    # source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.7/r_debugging_tools-v1.7.R") ; eval(parse(text = str_basic_arg_check_dev)) ; eval(parse(text = str_arg_check_with_fun_check_dev)) # activate this line and use the function (with no arguments left as NULL) to check arguments status and if they have been checked using fun_check()
    # end argument checking
    # main code
    if( ! (any(class(data1) %in% c("data.frame", "table")) | all(class(data1) %in% c("matrix", "array")))){ # before R4.0.0, it was  ! any(class(data1) %in% c("matrix", "data.frame", "table"))
        return(tail(data1, n))
    }else{
        obs.dim <- dim(data1)
        row <- ifelse(obs.dim[1] < n, 1, obs.dim[1] - n + 1):obs.dim[1]
        if(side == "l"){
            col <- 1:ifelse(obs.dim[2] < n, obs.dim[2], n)
        }
        if(side == "r"){
            col <- ifelse(obs.dim[2] < n, 1, obs.dim[2] - n + 1):obs.dim[2]
        }
        return(data1[row, col])
    }
Gael's avatar
tempo    
Gael committed
1109
}
1110
1111


Gael's avatar
Gael committed
1112
######## fun_comp_1d() #### comparison of two 1D datasets (vectors, factors, 1D tables)
1113
1114


Gael's avatar
Gael committed
1115
fun_comp_1d <- function(data1, data2){
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
    # AIM
    # compare two 1D datasets (vector or factor or 1D table, or 1D matrix or 1D array) of the same class or not. Check and report in a list if the 2 datasets have:
    # same class
    # common elements
    # common element names (except factors)
    # common levels (factors only)
    # ARGUMENTS
    # data1: vector or factor or 1D table, or 1D matrix or 1D array
    # data2: vector or factor or 1D table, or 1D matrix or 1D array
    # RETURN
    # a list containing:
    # $same.class: logical. Are class identical?
    # $class: class of the 2 datasets (NULL otherwise)
    # $same.length: logical. Are number of elements identical?
    # $length: number of elements in the 2 datasets (NULL otherwise)
    # $same.levels: logical. Are levels identical? NULL if data1 and data2 are not factors
    # $levels: levels of the 2 datasets if identical (NULL otherwise or NULL if data1 and data2 are not factors)
    # $any.id.levels: logical. Is there any identical levels? (NULL if data1 and data2 are not factors)
    # $same.levels.pos1: position, in data1, of the levels identical in data2 (NULL if data1 and data2 are not factors)
    # $same.levels.pos2: position, in data2, of the levels identical in data1 (NULL if data1 and data2 are not factors)
    # $common.levels: common levels between data1 and data2 (can be a subset of $levels or not). NULL if no common levels or if data1 and data2 are not factors
    # $same.name: logical. Are element names identical? NULL if data1 and data2 have no names
    # $name: name of elements of the 2 datasets if identical (NULL otherwise)
    # $any.id.name: logical. Is there any element names identical ?
    # $same.name.pos1: position, in data1, of the element names identical in data2. NULL if no identical names
    # $same.name.pos2: position, in data2, of the elements names identical in data1. NULL if no identical names
    # $common.names: common element names between data1 and data2 (can be a subset of $name or not). NULL if no common element names
    # $any.id.element: logical. is there any identical elements ?
    # $same.element.pos1: position, in data1, of the elements identical in data2. NULL if no identical elements
    # $same.element.pos2: position, in data2, of the elements identical in data1. NULL if no identical elements
    # $common.elements: common elements between data1 and data2. NULL if no common elements
    # $same.order: logical. Are all elements in the same order? TRUE or FALSE if elements of data1 and data2 are identical but not necessary in the same order. NULL otherwise (different length for instance)
    # $order1: order of all elements of data1. NULL if $same.order is FALSE
    # $order2: order of all elements of data2. NULL if $same.order is FALSE
    # $identical.object: logical. Are objects identical (kind of object, element names, content, including content order)?
    # $identical.content: logical. Are content objects identical (identical elements, including order, excluding kind of object and element names)?
    # REQUIRED PACKAGES
    # none
    # REQUIRED FUNCTIONS FROM CUTE_LITTLE_R_FUNCTION
    # none
    # EXAMPLES
    # obs1 = 1:5 ; obs2 = 1:5 ; names(obs1) <- LETTERS[1:5] ; names(obs2) <- LETTERS[1:5] ; fun_comp_1d(obs1, obs2)
    # obs1 = 1:5 ; obs2 = 1:5 ; names(obs1) <- LETTERS[1:5] ; fun_comp_1d(obs1, obs2)
    # obs1 = 1:5 ; obs2 = 3:6 ; names(obs1) <- LETTERS[1:5] ; names(obs2) <- LETTERS[1:4] ; fun_comp_1d(obs1, obs2)
    # obs1 = factor(LETTERS[1:5]) ; obs2 = factor(LETTERS[1:5]) ; fun_comp_1d(obs1, obs2)
    # obs1 = factor(LETTERS[1:5]) ; obs2 = factor(LETTERS[10:11]) ; fun_comp_1d(obs1, obs2)
    # obs1 = factor(LETTERS[1:5]) ; obs2 = factor(LETTERS[4:7]) ; fun_comp_1d(obs1, obs2)
    # obs1 = factor(c(LETTERS[1:4], "E")) ; obs2 = factor(c(LETTERS[1:4], "F")) ; fun_comp_1d(obs1, obs2)
    # obs1 = 1:5 ; obs2 = factor(LETTERS[1:5]) ; fun_comp_1d(obs1, obs2)
    # obs1 = 1:5 ; obs2 = 1.1:6.1 ; fun_comp_1d(obs1, obs2)
    # obs1 = as.table(1:5); obs2 = as.table(1:5) ; fun_comp_1d(obs1, obs2)
    # obs1 = as.table(1:5); obs2 = 1:5 ; fun_comp_1d(obs1, obs2)
    # DEBUGGING
    # data1 = 1:5 ; data2 = 1:5 ; names(data1) <- LETTERS[1:5] ; names(data2) <- LETTERS[1:5] # for function debugging
    # function name
    function.name <- paste0(as.list(match.call(expand.dots = FALSE))[[1]], "()")
    # end function name
    # argument checking
    if( ! any(class(data1) %in% c("logical", "integer", "numeric", "character", "factor", "table"))){
        tempo.cat <- paste0("ERROR IN ", function.name, ": THE data1 ARGUMENT MUST BE A NON NULL VECTOR, FACTOR OR 1D TABLE")
        stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
    }else if(all(class(data1) %in% "table")){
        if(length(dim(data1)) > 1){
            tempo.cat <- paste0("ERROR IN ", function.name, ": THE data1 ARGUMENT MUST BE A 1D TABLE")
            stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
        }
    }
    if( ! any(class(data2) %in% c("logical", "integer", "numeric", "character", "factor", "table"))){
        tempo.cat <- paste0("ERROR IN ", function.name, ": THE data2 ARGUMENT MUST BE A NON NULL VECTOR, FACTOR OR 1D TABLE")
        stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
    }else if(all(class(data2) %in% "table")){
        if(length(dim(data2)) > 1){
            tempo.cat <- paste0("ERROR IN ", function.name, ": THE data2 ARGUMENT MUST BE A 1D TABLE")
            stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
        }
    }
    # source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.7/r_debugging_tools-v1.7.R") ; eval(parse(text = str_basic_arg_check_dev)) # activate this line and use the function to check arguments status
    # end argument checking
    # main code
    same.class <- FALSE
    class <- NULL
    same.length <- FALSE
    length <- NULL
    same.levels <- NULL # not FALSE to deal with no factors
    levels <- NULL
    any.id.levels <- FALSE
    same.levels.pos1 <- NULL
    same.levels.pos2 <- NULL
    common.levels <- NULL
    same.name <- NULL # not FALSE to deal with absence of name
    name <- NULL
    any.id.name <- FALSE
    same.name.pos1 <- NULL
    same.name.pos2 <- NULL
    common.names <- NULL
    any.id.element <- FALSE
    same.element.pos1 <- NULL
    same.element.pos2 <- NULL
    common.elements <- NULL
    same.order <- NULL
    order1 <- NULL
    order2 <- NULL
    identical.object <- FALSE
    identical.content <- FALSE
    if(identical(data1, data2)){
        same.class <- TRUE
        class <- class(data1)
        same.length <- TRUE
        length <- length(data1)
        if(any(class(data1) %in% "factor")){
            same.levels <- TRUE
            levels <- levels(data1)
            any.id.levels <- TRUE
            same.levels.pos1 <- 1:length(levels(data1))
            same.levels.pos2 <- 1:length(levels(data2))
            common.levels <- levels(data1)
        }
        if( ! is.null(names(data1))){
            same.name <- TRUE
            name <- names(data1)
            any.id.name <- TRUE
            same.name.pos1 <- 1:length(data1)
            same.name.pos2 <- 1:length(data2)
            common.names <- names(data1)
        }
        any.id.element <- TRUE
        same.element.pos1 <- 1:length(data1)
        same.element.pos2 <- 1:length(data2)
        common.elements <- data1
        same.order <- TRUE
        order1 <- order(data1)
        order2 <- order(data2)
        identical.object <- TRUE
        identical.content <- TRUE
    }else{
        if(identical(class(data1), class(data2))){
            same.class <- TRUE
            class <- class(data1)
        }
        if(identical(length(data1), length(data2))){
            same.length<- TRUE
            length <- length(data1)
        }
        if(any(class(data1) %in% "factor") & any(class(data2) %in% "factor")){
            if(identical(levels(data1), levels(data2))){
                same.levels <- TRUE
                levels <- levels(data1)
            }else{
                same.levels <- FALSE
            }
            if(any(levels(data1) %in% levels(data2))){
                any.id.levels <- TRUE
                same.levels.pos1 <- which(levels(data1) %in% levels(data2))
            }
            if(any(levels(data2) %in% levels(data1))){
                any.id.levels <- TRUE
                same.levels.pos2 <- which(levels(data2) %in% levels(data1))
            }
            if(any.id.levels == TRUE){
                common.levels <- unique(c(levels(data1)[same.levels.pos1], levels(data2)[same.levels.pos2]))
            }
        }
        if(any(class(data1) %in% "factor")){ # to compare content
            data1 <- as.character(data1)
        }
        if(any(class(data2) %in% "factor")){ # to compare content
            data2 <- as.character(data2)
        }
        if( ! (is.null(names(data1)) & is.null(names(data2)))){
            if(identical(names(data1), names(data2))){
                same.name <- TRUE
                name <- names(data1)
            }else{
                same.name <- FALSE
            }
            if(any(names(data1) %in% names(data2))){
                any.id.name <- TRUE
                same.name.pos1 <- which(names(data1) %in% names(data2))
            }
            if(any(names(data2) %in% names(data1))){
                any.id.name <- TRUE
                same.name.pos2 <- which(names(data2) %in% names(data1))
            }
            if(any.id.name == TRUE){
                common.names <- unique(c(names(data1)[same.name.pos1], names(data2)[same.name.pos2]))
            }
        }
        names(data1) <- NULL # names solved -> to do not be disturbed by names
        names(data2) <- NULL # names solved -> to do not be disturbed by names
        if(any(data1 %in% data2)){
            any.id.element <- TRUE
            same.element.pos1 <- which(data1 %in% data2)
        }
        if(any(data2 %in% data1)){
            any.id.element <- TRUE
            same.element.pos2 <- which(data2 %in% data1)
        }
        if(any.id.element == TRUE){
            common.elements <- unique(c(data1[same.element.pos1], data2[same.element.pos2]))
        }
        if(identical(data1, data2)){
            identical.content <- TRUE
            same.order <- TRUE
        }else if(identical(sort(data1), sort(data2))){
            same.order <- FALSE
            order1 <- order(data1)
            order2 <- order(data2)
        }
    }
    output <- list(same.class = same.class, class = class, same.length = same.length, length = length, same.levels = same.levels, levels = levels, any.id.levels = any.id.levels, same.levels.pos1 = same.levels.pos1, same.levels.pos2 = same.levels.pos2, common.levels = common.levels, same.name = same.name, name = name, any.id.name = any.id.name, same.name.pos1 = same.name.pos1, same.name.pos2 = same.name.pos2, common.names = common.names, any.id.element = any.id.element, same.element.pos1 = same.element.pos1, same.element.pos2 = same.element.pos2, common.elements = common.elements, same.order = same.order, order1 = order1, order2 = order2, identical.object = identical.object, identical.content = identical.content)
    return(output)
Gael's avatar
Gael committed
1327
}
1328
1329


Gael's avatar
Gael committed
1330
######## fun_comp_2d() #### comparison of two 2D datasets (row & col names, dimensions, etc.)
1331

Gael's avatar
Gael committed
1332

Gael's avatar
Gael committed
1333
fun_comp_2d <- function(data1, data2){
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
    # AIM
    # compare two 2D datasets of the same class or not. Check and report in a list if the 2 datasets have:
    # same class
    # common row names
    # common column names
    # same row number
    # same column number
    # potential identical rows between the 2 datasets
    # potential identical columns between the 2 datasets
    # ARGUMENTS
    # data1: matrix, data frame or table
    # data2: matrix, data frame or table
    # RETURN
    # a list containing:
    # $same.class: logical. Are class identical ?
    # $class: classes of the 2 datasets (NULL otherwise)
    # $same.dim: logical. Are dimension identical ?
    # $dim: dimension of the 2 datasets (NULL otherwise)
    # $same.row.nb: logical. Are number of rows identical ?
    # $row.nb: nb of rows of the 2 datasets if identical (NULL otherwise)
    # $same.col.nb: logical. Are number of columns identical ?
    # $col.nb: nb of columns of the 2 datasets if identical (NULL otherwise)
    # $same.row.name: logical. Are row names identical ? NULL if no row names in the two 2D datasets
    # $row.name: name of rows of the 2 datasets if identical (NULL otherwise)
    # $any.id.row.name: logical. Is there any row names identical ? NULL if no row names in the two 2D datasets
    # $same.row.name.pos1: position, in data1, of the row names identical in data2
    # $same.row.name.pos2: position, in data2, of the row names identical in data1
    # $common.row.names: common row names between data1 and data2 (can be a subset of $name or not). NULL if no common row names
    # $same.col.name: logical. Are column names identical ? NULL if no col names in the two 2D datasets
    # $col.name: name of columns of the 2 datasets if identical (NULL otherwise)
    # $any.id.col.name: logical. Is there any column names identical ? NULL if no col names in the two 2D datasets
    # $same.col.name.pos1: position, in data1, of the column names identical in data2
    # $same.col.name.pos2: position, in data2, of the column names identical in data1
    # $common.col.names: common column names between data1 and data2 (can be a subset of $name or not). NULL if no common column names
    # $any.id.row: logical. is there identical rows (not considering row names)? NULL if nrow(data1) * nrow(data2) > 1e10
    # $same.row.pos1: position, in data1, of the rows identical in data2 (not considering row names). Return "TOO BIG FOR EVALUATION" if nrow(data1) * nrow(data2) > 1e10
    # $same.row.pos2: position, in data2, of the rows identical in data1 (not considering row names). Return "TOO BIG FOR EVALUATION" if nrow(data1) * nrow(data2) > 1e10
    # $any.id.col: logical. is there identical columns (not considering column names)? NULL if ncol(data1) * ncol(data2) > 1e10
    # $same.col.pos1: position in data1 of the cols identical in data2 (not considering column names). Return "TOO BIG FOR EVALUATION" if ncol(data1) * ncol(data2) > 1e10
    # $same.col.pos2: position in data2 of the cols identical in data1 (not considering column names). Return "TOO BIG FOR EVALUATION" if ncol(data1) * ncol(data2) > 1e10
    # $identical.object: logical. Are objects identical (including row & column names)?
    # $identical.content: logical. Are content objects identical (identical excluding row & column names)?
    # REQUIRED PACKAGES
    # none
    # REQUIRED FUNCTIONS FROM CUTE_LITTLE_R_FUNCTION
    # none
    # EXAMPLES
    # obs1 = matrix(1:10, ncol = 5, dimnames = list(letters[1:2], LETTERS[1:5])) ; obs2 = as.data.frame(matrix(1:10, ncol = 5, dimnames = list(letters[1:2], LETTERS[1:5])), stringsAsFactors = TRUE) ; obs1 ; obs2 ; fun_comp_2d(obs1, obs2)
    # obs1 = matrix(101:110, ncol = 5, dimnames = list(letters[1:2], LETTERS[1:5])) ; obs2 = matrix(1:10, ncol = 5, dimnames = list(letters[1:2], LETTERS[1:5])) ; obs1 ; obs2 ; fun_comp_2d(obs1, obs2)
    # large matrices
    # obs1 = matrix(1:1e6, ncol = 5, dimnames = list(NULL, LETTERS[1:5])) ; obs2 = matrix(as.integer((1:1e6)+1e6/5), ncol = 5, dimnames = list(NULL, LETTERS[1:5])) ; head(obs1) ; head(obs2) ; fun_comp_2d(obs1, obs2)
    # WARNING: when comparing content (rows, columns, or total), double and integer data are considered as different -> double(1) != integer(1)
    # obs1 = matrix(1:1e6, ncol = 5, dimnames = list(NULL, LETTERS[1:5])) ; obs2 = matrix((1:1e6)+1e6/5, ncol = 5, dimnames = list(NULL, LETTERS[1:5])) ; head(obs1) ; head(obs2) ; fun_comp_2d(obs1, obs2)
    # obs1 = matrix(1:10, byrow = TRUE, ncol = 5, dimnames = list(letters[1:2], LETTERS[1:5])) ; obs2 = matrix(c(1:5, 101:105, 6:10), byrow = TRUE, ncol = 5, dimnames = list(c("a", "z", "b"), c(LETTERS[1:2], "k", LETTERS[5:4]))) ; obs1 ; obs2 ; fun_comp_2d(obs1, obs2)
    # obs1 = t(matrix(1:10, byrow = TRUE, ncol = 5, dimnames = list(letters[1:2], LETTERS[1:5]))) ; obs2 = t(matrix(c(1:5, 101:105, 6:10), byrow = TRUE, ncol = 5, dimnames = list(c("a", "z", "b"), c(LETTERS[1:2], "k", LETTERS[5:4])))) ; obs1 ; obs2 ; fun_comp_2d(obs1, obs2)
    # DEBUGGING
    # data1 = matrix(1:10, ncol = 5) ; data2 = matrix(1:10, ncol = 5) # for function debugging
    # data1 = matrix(1:10, ncol = 5, dimnames = list(letters[1:2], LETTERS[1:5])) ; data2 = matrix(1:10, ncol = 5, dimnames = list(letters[1:2], LETTERS[1:5])) # for function debugging
    # data1 = matrix(1:10, ncol = 5, dimnames = list(letters[1:2], LETTERS[1:5])) ; data2 = matrix(1:10, ncol = 5) # for function debugging
    # data1 = matrix(1:15, byrow = TRUE, ncol = 5, dimnames = list(letters[1:3], LETTERS[1:5])) ; data2 = matrix(1:10, byrow = TRUE, ncol = 5, dimnames = list(letters[1:2], LETTERS[1:5])) # for function debugging
    # data1 = matrix(1:15, ncol = 5, dimnames = list(letters[1:3], LETTERS[1:5])) ; data2 = matrix(1:10, ncol = 5, dimnames = list(letters[1:2], LETTERS[1:5])) # for function debugging
    # data1 = matrix(1:15, ncol = 5, dimnames = list(paste0("A", letters[1:3]), LETTERS[1:5])) ; data2 = matrix(1:10, ncol = 5, dimnames = list(letters[1:2], LETTERS[1:5])) # for function debugging
    # data1 = matrix(1:15, ncol = 5, dimnames = list(letters[1:3], LETTERS[1:5])) ; data2 = matrix(1:12, ncol = 4, dimnames = list(letters[1:3], LETTERS[1:4])) # for function debugging
    # data1 = matrix(1:10, ncol = 5, dimnames = list(letters[1:2], LETTERS[1:5])) ; data2 = matrix(101:110, ncol = 5, dimnames = list(letters[1:2], LETTERS[1:5])) # for function debugging
    # data1 = data.frame(a = 1:3, b= letters[1:3], row.names = LETTERS[1:3], stringsAsFactors = TRUE) ; data2 = data.frame(A = 1:3, B= letters[1:3], stringsAsFactors = TRUE) # for function debugging
    # data1 = matrix(1:10, ncol = 5, dimnames = list(letters[1:2], LETTERS[1:5])) ; data2 = as.data.frame(matrix(1:10, ncol = 5, dimnames = list(letters[1:2], LETTERS[1:5])), stringsAsFactors = TRUE) # for function debugging
    # data1 = matrix(1:10, byrow = TRUE, ncol = 5, dimnames = list(letters[1:2], LETTERS[1:5])) ; data2 = matrix(c(1:5, 101:105, 6:10), byrow = TRUE, ncol = 5, dimnames = list(c("a", "z", "b"), c(LETTERS[1:2], "k", LETTERS[5:4]))) # for function debugging
    # data1 = table(Exp1 = c("A", "A", "A", "B", "B", "B"), Exp2 = c("A1", "B1", "A1", "C1", "C1", "B1")) ; data2 = data.frame(A = 1:3, B= letters[1:3], stringsAsFactors = TRUE) # for function debugging
    # data1 = matrix(1:1e6, ncol = 5, dimnames = list(NULL, LETTERS[1:5])) ; data2 = matrix((1:1e6)+1e6/5, ncol = 5, dimnames = list(NULL, LETTERS[1:5]))
    # function name
    function.name <- paste0(as.list(match.call(expand.dots = FALSE))[[1]], "()")
    # end function name
    # argument checking
    if( ! (any(class(data1) %in% c("data.frame", "table")) | all(class(data1) %in% c("matrix", "array")))){ # before R4.0.0, it was  ! any(class(data1) %in% c("matrix", "data.frame", "table"))
        tempo.cat <- paste0("ERROR IN ", function.name, ": THE data1 ARGUMENT MUST BE A MATRIX, DATA FRAME OR TABLE")
        stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
    }
    if( ! (any(class(data2) %in% c("data.frame", "table")) | all(class(data2) %in% c("matrix", "array")))){ # before R4.0.0, it was  ! any(class(data2) %in% c("matrix", "data.frame", "table"))
        tempo.cat <- paste0("ERROR IN ", function.name, ": THE data2 ARGUMENT MUST BE A MATRIX, DATA FRAME OR TABLE")
        stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
    }
    # source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.7/r_debugging_tools-v1.7.R") ; eval(parse(text = str_basic_arg_check_dev)) # activate this line and use the function to check arguments status
    # end argument checking
    # main code
    same.class <- NULL
    class <- NULL
    same.dim <- NULL
    dim <- NULL
    same.row.nb <- NULL
    row.nb <- NULL
    same.col.nb <- NULL
    col.nb <- NULL
    same.row.name <- NULL
    row.name <- NULL
    any.id.row.name <- NULL
    same.row.name.pos1 <- NULL
    same.row.name.pos2 <- NULL
    common.row.names <- NULL
    same.col.name <- NULL
    any.id.col.name <- NULL
    same.col.name.pos1 <- NULL
    same.col.name.pos2 <- NULL
    common.col.names <- NULL
    col.name <- NULL
    any.id.row <- NULL
    same.row.pos1 <- NULL
    same.row.pos2 <- NULL
    any.id.col <- NULL
    same.col.pos1 <- NULL
    same.col.pos2 <- NULL
    identical.object <- NULL
    identical.content <- NULL
    if(identical(data1, data2) & (any(class(data1) %in% c("data.frame", "table")) | all(class(data1) %in% c("matrix", "array")))){ # before R4.0.0, it was  ! any(class(data1) %in% c("matrix", "data.frame", "table"))
        same.class <- TRUE
        class <- class(data1)
        same.dim <- TRUE
        dim <- dim(data1)
        same.row.nb <- TRUE
        row.nb <- nrow(data1)
        same.col.nb <- TRUE
        col.nb <- ncol(data1)
        same.row.name <- TRUE
        row.name <- dimnames(data1)[[1]]
        any.id.row.name <- TRUE
        same.row.name.pos1 <- 1:row.nb
        same.row.name.pos2 <- 1:row.nb
        common.row.names <- dimnames(data1)[[1]]
        same.col.name <- TRUE
        col.name <- dimnames(data1)[[2]]
        any.id.col.name <- TRUE
        same.col.name.pos1 <- 1:col.nb
        same.col.name.pos2 <- 1:col.nb
        common.col.names <- dimnames(data1)[[2]]
        any.id.row <- TRUE
        same.row.pos1 <- 1:row.nb
        same.row.pos2 <- 1:row.nb
        any.id.col <- TRUE
        same.col.pos1 <- 1:col.nb
        same.col.pos2 <- 1:col.nb
        identical.object <- TRUE
        identical.content <- TRUE
    }else{
        identical.object <- FALSE
        if(all(class(data1) == "table") & length(dim(data1)) == 1L){
            tempo.cat <- paste0("ERROR IN ", function.name, ": THE data1 ARGUMENT IS A 1D TABLE. USE THE fun_comp_1d FUNCTION")
            stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
        }
        if(all(class(data2) == "table") & length(dim(data2)) == 1L){
            tempo.cat <- paste0("ERROR IN ", function.name, ": THE data2 ARGUMENT IS A 1D TABLE. USE THE fun_comp_1d FUNCTION")
            stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
        }
        if( ! identical(class(data1), class(data2))){
            same.class <- FALSE
        }else if( ! (any(class(data1) %in% c("data.frame", "table")) | all(class(data1) %in% c("matrix", "array")))){ # before R4.0.0, it was  ! any(class(data1) %in% c("matrix", "data.frame", "table"))
            tempo.cat <- paste0("ERROR IN ", function.name, ": THE data1 AND data2 ARGUMENTS MUST BE EITHER MATRIX, DATA FRAME OR TABLE")
            stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
        }else{
            same.class <- TRUE
            class <- class(data1)
        }
        if( ! identical(dim(data1), dim(data2))){
            same.dim <- FALSE
        }else{
            same.dim <- TRUE
            dim <- dim(data1)
        }
        if( ! identical(nrow(data1), nrow(data2))){
            same.row.nb <- FALSE
        }else{
            same.row.nb <- TRUE
            row.nb <- nrow(data1)
        }
        if( ! identical(ncol(data1), ncol(data2))){
            same.col.nb <- FALSE
        }else{
            same.col.nb <- TRUE
            col.nb <- ncol(data1)
        }
        # row and col names
        if(is.null(dimnames(data1)) & is.null(dimnames(data2))){
            same.row.name <- NULL
            same.col.name <- NULL
            # row and col names remain NULL
        }else if((is.null(dimnames(data1)) & ! is.null(dimnames(data2))) | ( ! is.null(dimnames(data1)) & is.null(dimnames(data2)))){
            same.row.name <- FALSE
            same.col.name <- FALSE
            # row and col names remain NULL
        }else{
            if( ! identical(dimnames(data1)[[1]], dimnames(data2)[[1]])){
                same.row.name <- FALSE
                # row names remain NULL
            }else{
                same.row.name <- TRUE
                row.name <- dimnames(data1)[[1]]
            }
            # row names
            any.id.row.name <- FALSE
            if(any(dimnames(data1)[[1]] %in% dimnames(data2)[[1]])){
                any.id.row.name <- TRUE
                same.row.name.pos1 <- which(dimnames(data1)[[1]] %in% dimnames(data2)[[1]])
            }
            if(any(dimnames(data2)[[1]] %in% dimnames(data1)[[1]])){
                any.id.row.name <- TRUE
                same.row.name.pos2 <- which(dimnames(data2)[[1]] %in% dimnames(data1)[[1]])
            }
            if(any.id.row.name == TRUE){
                common.row.names <- unique(c(dimnames(data1)[[1]][same.row.name.pos1], dimnames(data2)[[1]][same.row.name.pos2]))
            }
            # col names
            any.id.col.name <- FALSE
            if(any(dimnames(data1)[[2]] %in% dimnames(data2)[[2]])){
                any.id.col.name <- TRUE
                same.col.name.pos1 <- which(dimnames(data1)[[2]] %in% dimnames(data2)[[2]])
            }
            if(any(dimnames(data2)[[2]] %in% dimnames(data1)[[2]])){
                any.id.col.name <- TRUE
                same.col.name.pos2 <- which(dimnames(data2)[[2]] %in% dimnames(data1)[[2]])
            }
            if(any.id.col.name == TRUE){
                common.col.names <- unique(c(dimnames(data1)[[2]][same.col.name.pos1], dimnames(data2)[[2]][same.col.name.pos2]))
            }
            if( ! identical(dimnames(data1)[[2]], dimnames(data2)[[2]])){
                same.col.name <- FALSE
                # col names remain NULL
            }else{
                same.col.name <- TRUE
                col.name <- dimnames(data1)[[2]]
            }
        }
        # identical row and col content
        if(all(class(data1) == "table")){
            as.data.frame(matrix(data1, ncol = ncol(data1)), stringsAsFactors = FALSE)
        }else if(all(class(data1) %in% c("matrix", "array"))){
            data1 <- as.data.frame(data1, stringsAsFactors = FALSE)
        }else if(all(class(data1) == "data.frame")){
            data1 <- data.frame(lapply(data1, as.character), stringsAsFactors = FALSE)
        }
        if(all(class(data2) == "table")){
            as.data.frame(matrix(data2, ncol = ncol(data2)), stringsAsFactors = FALSE)
        }else if(all(class(data2) %in% c("matrix", "array"))){
            data2 <- as.data.frame(data2, stringsAsFactors = FALSE)
        }else if(all(class(data2) == "data.frame")){
            data2 <- data.frame(lapply(data2, as.character), stringsAsFactors = FALSE)
        }
        row.names(data1) <- paste0("A", 1:nrow(data1))
        row.names(data2) <- paste0("A", 1:nrow(data2))
        if(same.col.nb == TRUE){ # because if not the same col nb, the row cannot be identical
            if(all(sapply(data1, FUN = typeof) == "integer") & all(sapply(data2, FUN = typeof) == "integer") & as.double(nrow(data1)) * nrow(data2) <= 1e10){ # as.double(nrow(data1)) to prevent integer overflow because R is 32 bits for integers
                same.row.pos1 <- which(c(as.data.frame(t(data1), stringsAsFactors = FALSE)) %in% c(as.data.frame(t(data2), stringsAsFactors = FALSE))) # this work fast with only integers (because 32 bits)
                same.row.pos2 <- which(c(as.data.frame(t(data2), stringsAsFactors = FALSE)) %in% c(as.data.frame(t(data1), stringsAsFactors = FALSE)))
            }else if(as.double(nrow(data1)) * nrow(data2) <= 1e6){ # as.double(nrow(data1)) to prevent integer overflow because R is 32 bits for integers
                if(col.nb <= 10){ # if ncol is not to big, the t() should not be that long
                    same.row.pos1 <- which(c(as.data.frame(t(data1), stringsAsFactors = FALSE)) %in% c(as.data.frame(t(data2), stringsAsFactors = FALSE))) # this work fast with only integers (because 32 bits)
                    same.row.pos2 <- which(c(as.data.frame(t(data2), stringsAsFactors = FALSE)) %in% c(as.data.frame(t(data1), stringsAsFactors = FALSE)))
                }else{ # very long computation
                    same.row.pos1 <- logical(length = nrow(data1)) # FALSE by default
                    same.row.pos1[] <- FALSE # security
                    for(i3 in 1:nrow(data1)){
                        for(i4 in 1:nrow(data2)){
                            same.row.pos1[i3] <- identical(data1[i3, ], data2[i4, ])
                        }
                    }
                    same.row.pos1 <- which(same.row.pos1)
                    same.row.pos2 <- logical(length = nrow(data2)) # FALSE by default
                    same.row.pos2[] <- FALSE # security
                    for(i3 in 1:nrow(data2)){
                        for(i4 in 1:nrow(data1)){
                            same.row.pos2[i3] <- identical(data2[i3, ], data1[i4, ])
                        }
                    }
                    same.row.pos2 <- which(same.row.pos2)
                }
            }else{
                same.row.pos1 <- "TOO BIG FOR EVALUATION"
                same.row.pos2 <- "TOO BIG FOR EVALUATION"
            }
            
            names(same.row.pos1) <- NULL
            names(same.row.pos2) <- NULL
            if(all(is.na(same.row.pos1))){
                same.row.pos1 <- NULL
            }else{
                same.row.pos1 <- same.row.pos1[ ! is.na(same.row.pos1)]
                any.id.row <- TRUE
            }
            if(all(is.na(same.row.pos2))){
                same.row.pos2 <- NULL
            }else{
                same.row.pos2 <- same.row.pos2[ ! is.na(same.row.pos2)]
                any.id.row <- TRUE
            }
            if(is.null(same.row.pos1) & is.null(same.row.pos2)){
                any.id.row <- FALSE
            }else if(length(same.row.pos1) == 0L & length(same.row.pos2) == 0L){
                any.id.row <- FALSE
            }else if(all(same.row.pos1 == "TOO BIG FOR EVALUATION") & all(same.row.pos2 == "TOO BIG FOR EVALUATION")){
                any.id.row <- NULL
            }
        }else{
            any.id.row <- FALSE
            # same.row.pos1 and 2 remain NULL
        }
        if(same.row.nb == TRUE){ # because if not the same row nb, the col cannot be identical
            if(all(sapply(data1, FUN = typeof) == "integer") & all(sapply(data2, FUN = typeof) == "integer") & as.double(ncol(data1)) * ncol(data2) <= 1e10){ # as.double(ncol(data1)) to prevent integer overflow because R is 32 bits for integers
                same.col.pos1 <- which(c(data1) %in% c(data2))
                same.col.pos2 <- which(c(data2) %in% c(data1))
            }else if(as.double(ncol(data1)) * ncol(data2) <= 1e6){ # as.double(ncol(data1)) to prevent integer overflow because R is 32 bits for integers
                same.col.pos1 <- logical(length = ncol(data1)) # FALSE by default
                same.col.pos1[] <- FALSE # security
                for(i3 in 1:ncol(data1)){
                    for(i4 in 1:ncol(data2)){
                        same.col.pos1[i3] <- identical(data1[ , i3], data2[ ,i4])
                    }
                }
                same.col.pos1 <- which(same.col.pos1)
                
                same.col.pos2 <- logical(length = ncol(data2)) # FALSE by default
                same.col.pos2[] <- FALSE # security
                for(i3 in 1:ncol(data2)){
                    for(i4 in 1:ncol(data1)){
                        same.col.pos2[i3] <- identical(data2[ , i3], data1[ , i4])
                    }
                }
                same.col.pos2 <- which(same.col.pos2)
            }else{
                same.col.pos1 <- "TOO BIG FOR EVALUATION"
                same.col.pos2 <- "TOO BIG FOR EVALUATION"
            }
            names(same.col.pos1) <- NULL
            names(same.col.pos2) <- NULL
            if(all(is.na(same.col.pos1))){
                same.col.pos1 <- NULL
            }else{
                same.col.pos1 <- same.col.pos1[ ! is.na(same.col.pos1)]
                any.id.col <- TRUE
            }
            if(all(is.na(same.col.pos2))){
                same.col.pos2 <- NULL
            }else{
                same.col.pos2 <- same.col.pos2[ ! is.na(same.col.pos2)]
                any.id.col <- TRUE
            }
            if(is.null(same.col.pos1) & is.null(same.col.pos2)){
                any.id.col <- FALSE
            }else if(length(same.col.pos1) == 0L & length(same.col.pos2) == 0L){
                any.id.col <- FALSE
            }else if(all(same.col.pos1 == "TOO BIG FOR EVALUATION") & all(same.col.pos2 == "TOO BIG FOR EVALUATION")){
                any.id.col <- NULL
            }
        }else{
            any.id.col <- FALSE
            # same.col.pos1 and 2 remain NULL
        }
        if(same.dim == TRUE){
            names(data1) <- NULL
            row.names(data1) <- NULL
            names(data2) <- NULL
            row.names(data2) <- NULL
            if(identical(data1, data2)){
                identical.content <- TRUE
            }else{
                identical.content <- FALSE
            }
        }else{
            identical.content <- FALSE
        }
    }
    output <- list(same.class = same.class, class = class, same.dim = same.dim, dim = dim, same.row.nb = same.row.nb, row.nb = row.nb, same.col.nb = same.col.nb , col.nb = col.nb, same.row.name = same.row.name, row.name = row.name, any.id.row.name = any.id.row.name, same.row.name.pos1 = same.row.name.pos1, same.row.name.pos2 = same.row.name.pos2, common.row.names = common.row.names, same.col.name = same.col.name, col.name = col.name,any.id.col.name = any.id.col.name, same.col.name.pos1 = same.col.name.pos1, same.col.name.pos2 = same.col.name.pos2, common.col.names = common.col.names, any.id.row = any.id.row, same.row.pos1 = same.row.pos1, same.row.pos2 = same.row.pos2, any.id.col = any.id.col, same.col.pos1 = same.col.pos1, same.col.pos2 = same.col.pos2, identical.object = identical.object, identical.content = identical.content)
    return(output)
Gael's avatar
Gael committed
1703
}
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833


######## fun_comp_list() #### comparison of two lists


fun_comp_list <- function(data1, data2){
    # AIM
    # compare two lists. Check and report in a list if the 2 datasets have:
    # same length
    # common names
    # common compartments
    # ARGUMENTS
    # data1: list
    # data2: list
    # RETURN
    # a list containing:
    # $same.length: logical. Are number of elements identical?
    # $length: number of elements in the 2 datasets (NULL otherwise)
    # $same.name: logical. Are element names identical ?
    # $name: name of elements of the 2 datasets if identical (NULL otherwise)
    # $any.id.name: logical. Is there any element names identical ?
    # $same.name.pos1: position, in data1, of the element names identical in data2
    # $same.name.pos2: position, in data2, of the compartment names identical in data1
    # $any.id.compartment: logical. is there any identical compartments ?
    # $same.compartment.pos1: position, in data1, of the compartments identical in data2
    # $same.compartment.pos2: position, in data2, of the compartments identical in data1
    # $identical.object: logical. Are objects identical (kind of object, compartment names and content)?
    # $identical.content: logical. Are content objects identical (identical compartments excluding compartment names)?
    # REQUIRED PACKAGES
    # none
    # REQUIRED FUNCTIONS FROM CUTE_LITTLE_R_FUNCTION
    # none
    # EXAMPLES
    # obs1 = list(a = 1:5, b = LETTERS[1:2], d = matrix(1:6)) ; obs2 = list(a = 1:5, b = LETTERS[1:2], d = matrix(1:6)) ; fun_comp_list(obs1, obs2)
    # obs1 = list(1:5, LETTERS[1:2]) ; obs2 = list(a = 1:5, b = LETTERS[1:2]) ; fun_comp_list(obs1, obs2)
    # obs1 = list(b = 1:5, c = LETTERS[1:2]) ; obs2 = list(a = 1:5, b = LETTERS[1:2], d = matrix(1:6)) ; fun_comp_list(obs1, obs2)
    # obs1 = list(b = 1:5, c = LETTERS[1:2]) ; obs2 = list(LETTERS[5:9], matrix(1:6), 1:5) ; fun_comp_list(obs1, obs2)
    # DEBUGGING
    # data1 = list(a = 1:5, b = LETTERS[1:2], d = matrix(1:6)) ; data2 = list(a = 1:5, b = LETTERS[1:2], d = matrix(1:6)) # for function debugging
    # data1 = list(a = 1:5, b = LETTERS[1:2]) ; data2 = list(a = 1:5, b = LETTERS[1:2], d = matrix(1:6)) # for function debugging
    # function name
    function.name <- paste0(as.list(match.call(expand.dots = FALSE))[[1]], "()")
    # end function name
    # argument checking
    if( ! any(class(data1) %in% "list")){
        tempo.cat <- paste0("ERROR IN ", function.name, ": THE data1 ARGUMENT MUST BE A LIST")
        stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
    }
    if( ! any(class(data2) %in% "list")){
        tempo.cat <- paste0("ERROR IN ", function.name, ": THE data2 ARGUMENT MUST BE A LIST")
        stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
    }
    # source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.7/r_debugging_tools-v1.7.R") ; eval(parse(text = str_basic_arg_check_dev)) # activate this line and use the function to check arguments status
    # end argument checking
    # main code
    same.length <- NULL
    length <- NULL
    same.name <- NULL
    name <- NULL
    any.id.name <- NULL
    same.name.pos1 <- NULL
    same.name.pos2 <- NULL
    any.id.compartment <- NULL
    same.compartment.pos1 <- NULL
    same.compartment.pos2 <- NULL
    identical.object <- NULL
    identical.content <- NULL
    if(identical(data1, data2)){
        same.length <- TRUE
        length <- length(data1)
        if( ! is.null(names(data1))){
            same.name <- TRUE
            name <- names(data1)
            any.id.name <- TRUE
            same.name.pos1 <- 1:length(data1)
            same.name.pos2 <- 1:length(data2)
        }
        any.id.compartment <- TRUE
        same.compartment.pos1 <- 1:length(data1)
        same.compartment.pos2 <- 1:length(data2)
        identical.object <- TRUE
        identical.content <- TRUE
    }else{
        identical.object <- FALSE
        if( ! identical(length(data1), length(data2))){
            same.length<- FALSE
        }else{
            same.length<- TRUE
            length <- length(data1)
        }
        if( ! (is.null(names(data1)) & is.null(names(data2)))){
            if( ! identical(names(data1), names(data2))){
                same.name <- FALSE
            }else{
                same.name <- TRUE
                name <- names(data1)
            }
            any.id.name <- FALSE
            if(any(names(data1) %in% names(data2))){
                any.id.name <- TRUE
                same.name.pos1 <- which(names(data1) %in% names(data2))
            }
            if(any(names(data2) %in% names(data1))){
                any.id.name <- TRUE
                same.name.pos2 <- which(names(data2) %in% names(data1))
            }
        }
        names(data1) <- NULL
        names(data2) <- NULL
        any.id.compartment <- FALSE
        if(any(data1 %in% data2)){
            any.id.compartment <- TRUE
            same.compartment.pos1 <- which(data1 %in% data2)
        }
        if(any(data2 %in% data1)){
            any.id.compartment <- TRUE
            same.compartment.pos2 <- which(data2 %in% data1)
        }
        if(same.length == TRUE & ! all(is.null(same.compartment.pos1), is.null(same.compartment.pos2))){
            if(identical(same.compartment.pos1, same.compartment.pos2)){
                identical.content <- TRUE
            }else{
                identical.content <- FALSE
            }
        }else{
            identical.content <- FALSE
        }
    }
    output <- list(same.length = same.length, length = length, same.name = same.name, name = name, any.id.name = any.id.name, same.name.pos1 = same.name.pos1, same.name.pos2 = same.name.pos2, any.id.compartment = any.id.compartment, same.compartment.pos1 = same.compartment.pos1, same.compartment.pos2 = same.compartment.pos2, identical.object = identical.object, identical.content = identical.content)
    return(output)
Gael's avatar
Gael committed
1834
}
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232


######## fun_test() #### test combinations of argument values of a function and return errors (and graphs)


# add traceback https://stackoverflow.com/questions/47414119/how-to-read-a-traceback-in-r

fun_test <- function(
    fun, 
    arg, 
    val, 
    expect.error = NULL, 
    thread.nb = NULL, 
    print.count = 10, 
    plot.fun = FALSE, 
    export = FALSE, 
    res.path = NULL, 
    lib.path = NULL, 
    cute.path = "C:\\Users\\Gael\\Documents\\Git_projects\\cute_little_R_functions\\cute_little_R_functions.R"
){
    # AIM
    # test combinations of argument values of a function
    # WARNINGS
    # Limited to 43 arguments with at least 2 values each. The total number of arguments tested can be more if the additional arguments have a single value. The limit is due to nested "for" loops (https://stat.ethz.ch/pipermail/r-help/2008-March/157341.html), but it should not be a problem since the number of tests would be 2^43 > 8e12
    # ARGUMENTS
    # fun: character string indicating the name of the function tested (without brackets)
    # arg: vector of character strings of arguments of fun. At least arguments that do not have default values must be present in this vector
    # val: list with number of compartments equal to length of arg, each compartment containing values of the corresponding argument in arg. Each different value must be in a list or in a vector. For instance, argument 3 in arg is a logical argument (values accepted TRUE, FALSE, NA). Thus, compartment 3 of val can be either list(TRUE, FALSE, NA), or c(TRUE, FALSE, NA). NULL value alone must be written list(NULL)
    # expect.error: list of exactly the same structure as val argument, but containing FALSE or TRUE, depending on whether error is expected (TRUE) or not (FALSE) for each corresponding value of val. A message is returned depending on discrepancies between the expected and observed errors. BEWARE: not always possible to write the expected errors for all the combination of argument values. Ignored if NULL
    # thread.nb: numeric value indicating the number of available threads. Write NULL if no parallelization wanted
    # print.count: interger value. Print a working progress message every print.count during loops. BEWARE: can increase substentially the time to complete the process using a small value, like 10 for instance. Use Inf is no loop message desired
    # plot.fun: logical. Plot the plotting function tested for each test?
    # export: logical. Export the results into a .RData file and into a .txt file? If FALSE, return a list into the console (see below). BEWARE: will be automatically set to TRUE if thread.nb is not NULL. This means that when using parallelization, the results are systematically exported, not returned into the console
    # res.path: character string indicating the absolute pathway of folder where the txt results and pdfs, containing all the plots, will be saved. Several txt and pdf, one per thread, if parallelization. Ignored if export is FALSE. Must be specified if thread.nb is not NULL or if export is TRUE
    # lib.path: character vector specifying the absolute pathways of the directories containing the required packages if not in the default directories. Ignored if NULL
    # cute.path: character string indicating the absolute path of the cute.R file. Will be remove when cute will be a package. Not considered if thread.nb is NULL
    # REQUIRED PACKAGES
    # lubridate
    # parallel if thread.nb argument is not NULL (included in the R installation packages but not automatically loaded)
    # pdftools if thread.nb argument is not NULL (included in the R installation packages but not automatically loaded)
    # If the tested function is in a package, this package must be imported first (no parallelization) or must be in the classical R package folder indicated by the lib.path argument (parallelization)
    # RETURN
    # if export is FALSE a list containing:
    # $fun: the tested function
    # $instruction: the initial instruction
    # $sys.info: system and packages info
    # $data: a data frame of all the combination tested, containing the following columns:
    # the different values tested, named by arguments
    # $kind: a vector of character strings indicating the kind of test result: either "ERROR", or "WARNING", or "OK"
    # $problem: a logical vector indicating if error or not
    # $expected.error: optional logical vector indicating the expected error specified in the expect.error argument
    # $message: either NULL if $kind is always "OK", or the messages
    # if export is TRUE 1) the same list object into a .RData file, 2) also the $data data frame into a .txt file, and 3) if expect.error is non NULL and if any discrepancy, the $data data frame into a .txt file but containing only the rows with discrepancies between expected and observed errors
    # one or several pdf if a plotting function is tested and if the plot.fun argument is TRUE
    # REQUIRED PACKAGES
    # none
    # REQUIRED FUNCTIONS FROM CUTE_LITTLE_R_FUNCTION
    # fun_check()
    # fun_get_message()
    # fun_pack()
    # EXAMPLES
    # fun_test(fun = "unique", arg = c("x", "incomparables"), val = list(x = list(1:10, c(1,1,2,8), NA), incomparable = c(TRUE, FALSE, NA)))
    # fun_test(fun = "fun_round", arg = c("data", "dec.nb", "after.lead.zero"), val = list(L1 = list(c(1, 1.0002256, 1.23568), "a", NA), L2 = list(2, c(1,3), NA), L3 = c(TRUE, FALSE, NA)))
    # fun_test(fun = "plot", arg = c("x", "y"), val = list(x = list(1:10, 12:13, NA, (1:10)^2), y = list(1:10, NA, NA)),  expect.error = list(x = list(FALSE, TRUE, TRUE, FALSE), y = list(FALSE, TRUE, TRUE)), thread.nb = NULL, plot.fun = TRUE, res.path = "C:\\Users\\Gael\\Desktop\\", lib.path = NULL)
    # fun_test(fun = "plot", arg = c("x", "y"), val = list(x = list(1:10, 12:13, NA, (1:10)^2), y = list(1:10, NA, NA)), thread.nb = 4, plot.fun = TRUE, res.path = "C:\\Users\\Gael\\Desktop\\", lib.path = "C:\\Program Files\\R\\R-4.0.2\\library\\")
    # set.seed(1) ; obs1 <- data.frame(Time = c(rnorm(10), rnorm(10) + 2), Group1 = rep(c("G", "H"), each = 10), stringsAsFactors = TRUE) ; fun_test(fun = "fun_gg_boxplot", arg = c("data1", "y", "categ"), val = list(L1 = list(L1 = obs1), L2 = list(L1 = "Time"), L3 = list(L1 = "Group1")))
    # set.seed(1) ; obs1 <- data.frame(Time = c(rnorm(10), rnorm(10) + 2), Group1 = rep(c("G", "H"), each = 10), stringsAsFactors = TRUE) ; fun_test(fun = "fun_gg_boxplot", arg = c("data1", "y", "categ"), val = list(L1 = list(obs1), L2 = "Time", L3 = "Group1"), thread.nb = NULL, plot.fun = TRUE, res.path = "C:\\Users\\Gael\\Desktop\\", lib.path = "C:\\Program Files\\R\\R-4.0.2\\library\\")
    # library(ggplot2) ; fun_test(fun = "geom_histogram", arg = c("data", "mapping"), val = list(x = list(data.frame(X = "a", stringsAsFactors = TRUE)), y = list(ggplot2::aes(x = X))), thread.nb = NULL, plot.fun = TRUE, res.path = "C:\\Users\\Gael\\Desktop\\", lib.path = "C:\\Program Files\\R\\R-4.0.2\\library\\") # BEWARE: ggplot2::geom_histogram does not work
    # DEBUGGING
    # fun = "unique" ; arg = "x" ; val = list(x = list(1:10, c(1,1,2,8), NA)) ; expect.error = list(x = list(FALSE, FALSE, TRUE)) ; thread.nb = NULL ; plot.fun = FALSE ; export = FALSE ; res.path = "C:\\Users\\Gael\\Desktop\\" ; lib.path = NULL ; print.count = 1 ; cute.path = "C:\\Users\\Gael\\Documents\\Git_projects\\cute_little_R_functions\\cute_little_R_functions.R" # for function debugging
    # fun = "unique" ; arg = c("x", "incomparables") ; val = list(x = list(1:10, c(1,1,2,8), NA), incomparable = c(TRUE, FALSE, NA)) ; expect.error = NULL ; thread.nb = 2 ; plot.fun = FALSE ; export = TRUE ; res.path = "C:\\Users\\Gael\\Desktop\\" ; lib.path = NULL ; print.count = 10 ; cute.path = "C:\\Users\\Gael\\Documents\\Git_projects\\cute_little_R_functions\\cute_little_R_functions.R" # for function debugging
    # fun = "plot" ; arg = c("x", "y") ; val = list(x = list(1:10, 12:13, NA), y = list(1:10, NA, NA)) ; expect.error = list(x = list(FALSE, FALSE, TRUE, FALSE), y = list(FALSE, TRUE, TRUE)) ; print.count = 10 ; thread.nb = NULL ; plot.fun = TRUE ; export = TRUE ; res.path = "C:\\Users\\Gael\\Desktop\\" ; lib.path = NULL # for function debugging
    # set.seed(1) ; obs1 <- data.frame(Time = c(rnorm(10), rnorm(10) + 2), Group1 = rep(c("G", "H"), each = 10), stringsAsFactors = TRUE) ; fun = "fun_gg_boxplot" ; arg = c("data1", "y", "categ") ; val = list(L1 = list(L1 = obs1), L2 = list(L1 = "Time"), L3 = list(L1 = "Group1")) ; expect.error = NULL ; print.count = 10 ; thread.nb = NULL ; plot.fun = TRUE ; export = TRUE ; res.path = "C:\\Users\\Gael\\Desktop\\" ; lib.path = NULL # for function debugging
    # fun = "unique" ; arg = "x" ; val = list(list(1:3, mean)) ; expect.error = list(TRUE, TRUE) ; thread.nb = NULL ; plot.fun = FALSE ; export = FALSE ; res.path = "C:\\Users\\Gael\\Desktop\\" ; lib.path = NULL ; print.count = 1 ; cute.path = "C:\\Users\\Gael\\Documents\\Git_projects\\cute_little_R_functions\\cute_little_R_functions.R" # for function debugging
    # function name
    function.name <- paste0(as.list(match.call(expand.dots = FALSE))[[1]], "()")
    instruction <- match.call()
    # end function name
    # required function checking
    req.function <- c(
        "fun_check", 
        "fun_get_message", 
        "fun_pack"
    )
    for(i1 in req.function){
        if(base::length(find(i1, mode = "function")) == 0L){
            tempo.cat <- paste0("ERROR IN ", function.name, ": REQUIRED ", i1, "() FUNCTION IS MISSING IN THE R ENVIRONMENT")
            stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
        }
    }
    # end required function checking
    # argument primary checking
    # arg with no default values
    if(any(missing(fun) | missing(arg) | missing(val))){
        tempo.cat <- paste0("ERROR IN ", function.name, ": ARGUMENTS fun, arg AND val HAVE NO DEFAULT VALUE AND REQUIRE ONE")
        stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
    }
    # end arg with no default values
    # using fun_check()
    arg.check <- NULL #
    text.check <- NULL #
    checked.arg.names <- NULL # for function debbuging: used by r_debugging_tools
    ee <- expression(arg.check <- c(arg.check, tempo$problem) , text.check <- c(text.check, tempo$text) , checked.arg.names <- c(checked.arg.names, tempo$object.name))
    tempo <- fun_check(data = fun, class = "vector", mode = "character", length = 1, fun.name = function.name) ; eval(ee)
    if(tempo$problem == FALSE){
        if(grepl(x = fun, pattern = "()$")){ # remove ()
            fun <- sub(x = fun, pattern = "()$", replacement = "")
        }
        if( ! exists(fun)){
            tempo.cat <- paste0("ERROR IN ", function.name, ": CHARACTER STRING IN fun ARGUMENT DOES NOT EXIST IN THE R WORKING ENVIRONMENT: ", paste(fun, collapse = "\n"))
            text.check <- c(text.check, tempo.cat)
            arg.check <- c(arg.check, TRUE)
        }else if( ! all(base::class(get(fun)) == "function")){ # here no env = sys.nframe(), inherit = FALSE for get() because fun is a function in the classical scope
            tempo.cat <- paste0("ERROR IN ", function.name, ": fun ARGUMENT IS NOT CLASS \"function\" BUT: ", paste(base::class(get(fun)), collapse = "\n"), "\nCHECK IF ANY CREATED OBJECT WOULD HAVE THE NAME OF THE TESTED FUNCTION")
            text.check <- c(text.check, tempo.cat)
            arg.check <- c(arg.check, TRUE)
        }
    }
    tempo <- fun_check(data = arg, class = "vector", mode = "character", fun.name = function.name) ; eval(ee)
    if(tempo$problem == FALSE & base::length(arg) == 0L){
        tempo.cat <- paste0("ERROR IN ", function.name, ": arg ARGUMENT CANNOT BE LENGTH 0")
        text.check <- c(text.check, tempo.cat)
        arg.check <- c(arg.check, TRUE)
    }
    tempo <- fun_check(data = val, class = "list", fun.name = function.name) ; eval(ee)
    if(tempo$problem == FALSE){
        for(i2 in 1:base::length(val)){
            tempo1 <- fun_check(data = val[[i2]], class = "vector", na.contain = TRUE, fun.name = function.name)
            tempo2 <- fun_check(data = val[[i2]], class = "list", na.contain = TRUE, fun.name = function.name)
            if(tempo1$problem == TRUE & tempo2$problem == TRUE){
                tempo.cat <- paste0("ERROR IN ", function.name, ": COMPARTMENT ", i2, " OF val ARGUMENT MUST BE A VECTOR OR A LIST")
                text.check <- c(text.check, tempo.cat)
                arg.check <- c(arg.check, TRUE)
            }else if(tempo1$problem == FALSE){ # vector split into list compartments
                val[[i2]] <- split(x = val[[i2]], f = 1:base::length(val[[i2]]))
            }
        }
    }
    if( ! is.null(expect.error)){
        tempo <- fun_check(data = expect.error, class = "list", fun.name = function.name) ; eval(ee)
        if(tempo$problem == FALSE){
            for(i3 in 1:base::length(expect.error)){
                tempo1 <- fun_check(data = expect.error[[i3]], class = "vector",  mode = "logical", fun.name = function.name)
                tempo2 <- fun_check(data =  expect.error[[i3]], class = "list", fun.name = function.name)
                if(tempo1$problem == TRUE & tempo2$problem == TRUE){
                    tempo.cat <- paste0("ERROR IN ", function.name, ": COMPARTMENT ", i3, " OF expect.error ARGUMENT MUST BE TRUE OR FALSE")
                    text.check <- c(text.check, tempo.cat)
                    arg.check <- c(arg.check, TRUE)
                }else if(tempo1$problem == FALSE){ # vector split into list compartments
                    expect.error[[i3]] <- split(x = expect.error[[i3]], f = 1:base::length(expect.error[[i3]]))
                }
            }
        }
    }
    if( ! is.null(thread.nb)){
        tempo <- fun_check(data = thread.nb, typeof = "integer", double.as.integer.allowed = TRUE, neg.values = FALSE, length = 1, fun.name = function.name) ; eval(ee)
        if(tempo$problem == FALSE & thread.nb < 1){
            tempo.cat <- paste0("ERROR IN ", function.name, ": thread.nb PARAMETER MUST EQUAL OR GREATER THAN 1: ", thread.nb)
            text.check <- c(text.check, tempo.cat)
            arg.check <- c(arg.check, TRUE)
        }
    }
    tempo <- fun_check(data = print.count, class = "vector", typeof = "integer", length = 1, double.as.integer.allowed = TRUE, neg.values = FALSE, fun.name = function.name) ; eval(ee)
    tempo <- fun_check(data = plot.fun, class = "vector", mode = "logical", length = 1, fun.name = function.name) ; eval(ee)
    tempo <- fun_check(data = export, class = "vector", mode = "logical", length = 1, fun.name = function.name) ; eval(ee)
    if( ! is.null(res.path)){
        tempo <- fun_check(data = res.path, class = "vector", mode = "character", fun.name = function.name) ; eval(ee)
        if(tempo$problem == FALSE){
            if( ! all(dir.exists(res.path))){ # separation to avoid the problem of tempo$problem == FALSE and res.path == NA
                tempo.cat <- paste0("ERROR IN ", function.name, ": DIRECTORY PATH INDICATED IN THE res.path ARGUMENT DOES NOT EXISTS:\n", paste(res.path, collapse = "\n"))
                text.check <- c(text.check, tempo.cat)
                arg.check <- c(arg.check, TRUE)
            }
        }
    }
    if( ! is.null(lib.path)){
        tempo <- fun_check(data = lib.path, class = "vector", mode = "character", fun.name = function.name) ; eval(ee)
        if(tempo$problem == FALSE){
            if( ! all(dir.exists(lib.path))){ # separation to avoid the problem of tempo$problem == FALSE and lib.path == NA
                tempo.cat <- paste0("ERROR IN ", function.name, ": DIRECTORY PATH INDICATED IN THE lib.path ARGUMENT DOES NOT EXISTS:\n", paste(lib.path, collapse = "\n"))
                text.check <- c(text.check, tempo.cat)
                arg.check <- c(arg.check, TRUE)
            }
        }
    }
    if( ! is.null(thread.nb)){
        tempo <- fun_check(data = cute.path, class = "vector", typeof = "character", length = 1, fun.name = function.name) ; eval(ee)
        if(tempo$problem == FALSE){
            if( ! file.exists(cute.path)){
                tempo.cat <- paste0("ERROR IN ", function.name, ": FILE PATH INDICATED IN THE cute.path PARAMETER DOES NOT EXISTS:\n", cute.path)
                text.check <- c(text.check, tempo.cat)
                arg.check <- c(arg.check, TRUE)
            }
        }
    }
    if(any(arg.check) == TRUE){
        stop(paste0("\n\n================\n\n", paste(text.check[arg.check], collapse = "\n"), "\n\n================\n\n"), call. = FALSE) #
    }
    # end using fun_check()
    # source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.7/r_debugging_tools-v1.7.R") ; eval(parse(text = str_basic_arg_check_dev)) ; eval(parse(text = str_arg_check_with_fun_check_dev)) # activate this line and use the function (with no arguments left as NULL) to check arguments status and if they have been checked using fun_check()
    # end argument primary checking
    # second round of checking and data preparation
    # management of NA
    if(any(is.na(fun)) | any(is.na(arg)) | any(is.na(expect.error)) | any(is.na(thread.nb)) | any(is.na(print.count)) | any(is.na(plot.fun)) | any(is.na(export)) | any(is.na(res.path)) | any(is.na(lib.path))){
        tempo.cat <- paste0("ERROR IN ", function.name, ": NO ARGUMENT EXCEPT val CAN HAVE NA VALUES")
        stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
    }
    # end management of NA
    # management of NULL
    if(is.null(fun) | is.null(arg) | is.null(val) | is.null(print.count) | is.null(plot.fun) | is.null(export)){
        tempo.cat <- paste0("ERROR IN ", function.name, ": THESE ARGUMENTS\nfun\narg\nval\nprint.count\nplot.fun\nexport\nCANNOT BE NULL") #problematic arguments are -> put everywhere
        stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
    }
    # end management of NULL
    if(base::length(arg) != base::length(val)){
        tempo.cat <- paste0("ERROR IN ", function.name, ": LENGTH OF arg ARGUMENT MUST BE IDENTICAL TO LENGTH OF val ARGUMENT:\nHERE IT IS: ", base::length(arg), " VERSUS ", base::length(val))
        stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE)
    }
    args <- names(formals(get(fun))) # here no env = sys.nframe(), inherit = FALSE for get() because fun is a function in the classical scope
    if( ! all(arg %in% args)){
        tempo.cat <- paste0("ERROR IN ", function.name, ": SOME OF THE STRINGS IN arg ARE NOT ARGUMENTS OF fun\nfun ARGUMENTS: ", paste(args, collapse = " "),"\nPROBLEMATIC STRINGS IN arg: ", paste(arg[ ! arg %in% args], collapse = " "))
        stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE)
    }
    if(sum(sapply(val, FUN = length) > 1) > 43){
        tempo.cat <- paste0("ERROR IN ", function.name, ": CANNOT TEST MORE THAN 43 ARGUMENTS IF THEY ALL HAVE AT LEAST 2 VALUES EACH\nHERE THE NUMBER IS: ", sum(sapply(val, FUN = length) > 1))
        stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE)
    }
    if( ! is.null(expect.error)){
        if(base::length(val) != base::length(expect.error)){
            tempo.cat <- paste0("ERROR IN ", function.name, ": LENGTH OF val ARGUMENT MUST BE IDENTICAL TO LENGTH OF expect.error ARGUMENT:\nHERE IT IS: ", base::length(val), " VERSUS ", base::length(expect.error))
            stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE)
        }
    }
    if( ! is.null(thread.nb) & is.null(res.path)){
        tempo.cat <- paste0("ERROR IN ", function.name, ": res.path ARGUMENT MUST BE SPECIFIED IF thread.nb ARGUMENT IS NOT NULL")
        stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE)
    }
    if(is.null(res.path) & export == TRUE){
        tempo.cat <- paste0("ERROR IN ", function.name, ": res.path ARGUMENT MUST BE SPECIFIED IF export ARGUMENT TRUE")
        stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE)
    }
    if( ! is.null(thread.nb) & export == FALSE){
        export <- TRUE
        tempo.cat <- paste0("WARNING FROM ", function.name, ": export ARGUMENT CONVERTED TO TRUE BECAUSE thread.nb ARGUMENT IS NOT NULL")
        warning(paste0("\n", tempo.cat, "\n"), call. = FALSE)
    }
    # end second round of checking and data preparation
    # package checking
    fun_pack(req.package = c("lubridate", "pdftools"), lib.path = lib.path)
    if( ! is.null(thread.nb)){
        fun_pack(req.package = c("parallel"), lib.path = lib.path)
    }
    # end package checking
    # declaration of special plot functions
    sp.plot.fun <- c("fun_gg_scatter", "fun_gg_bar", "fun_gg_boxplot")
    # end declaration of special plot functions
    # main code
    ini.warning.length <- base::options()$warning.length
    options(warning.length = 8170)
    warn <- NULL
    warn.count <- 0
    cat("\nfun_test JOB IGNITION\n")
    ini.date <- Sys.time()
    ini.time <- as.numeric(ini.date) # time of process begin, converted into seconds
    if(export == TRUE){
        res.path <- paste0(res.path, "/fun_test_res_", trunc(ini.time))
        if(dir.exists(res.path)){
            tempo.cat <- paste0("ERROR IN ", function.name, ": FOLDER ALREADY EXISTS\n", res.path, "\nPLEASE RERUN ONCE")
            stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
        }else{
            dir.create(res.path)
        }
    }
    total.comp.nb <- prod(sapply(val, FUN = "length"))
    cat(paste0("\nTHE TOTAL NUMBER OF TESTS IS: ", total.comp.nb, "\n"))
    # creation of the txt instruction that includes several loops
    loop.string <- NULL
    end.loop.string <- NULL
    fun.args <- NULL
    fun.args2 <- NULL
    error.values <- NULL
    arg.values <- "list("
    for(i1 in 1:base::length(arg)){
        if(is.null(thread.nb)){
            if(base::length(val[[i1]]) > 1){ # loop only if more than one value in base::length(val[[i1]])
                loop.string <- paste0(loop.string, "for(i", i1, " in 1:", base::length(val[[i1]]), "){")
                end.loop.string <- paste0(end.loop.string, "}")
            }
        }else{
            loop.string <- "for(i in x){"
            end.loop.string <- "}"
        }
        fun.args <- paste0(
            fun.args, 
            ifelse(i1 == 1L, "", ", "), 
            arg[i1], 
            " = val[[", 
            i1, 
            "]][[", 
            if(is.null(thread.nb)){
                if(base::length(val[[i1]]) > 1){
                    paste0("i", i1)
                }else{
                    "1" # a unique element in val[[i1]]
                }
            }else{
                paste0("i.list[[", i1, "]][i]")
            }, 
            "]]"
        )
        fun.args2 <- paste0(
            fun.args2, 
            ifelse(i1 == 1L, "", ", "), 
            arg[i1], 
            " = val[[", 
            i1, 
            "]][[', ", 
            if(is.null(thread.nb)){
                if(base::length(val[[i1]]) > 1){
                    paste0("i", i1)
                }else{
                    "1" # a unique element in val[[i1]]
                }
            }else{
                paste0("i.list[[", i1, "]][i]")
            }, 
            ", ']]"
        )
        arg.values <- paste0(
            arg.values, 
            "val[[", i1, "]][[", 
            if(is.null(thread.nb)){
                if(base::length(val[[i1]]) > 1){
                    paste0("i", i1)
                }else{
                    "1" # a unique element in val[[i1]]
                }
            }else{
                paste0("i.list[[", i1, "]][i]")
            }, 
            "]]", 
            ifelse(i1 == base::length(arg), "", ", ")
        )
        error.values <- paste0(
            error.values, 
            ifelse(i1 == 1L, "", " | "), 
            "expect.error[[", i1, "]][[", 
            if(is.null(thread.nb)){
                if(base::length(expect.error[[i1]]) > 1){
                    paste0("i", i1)
                }else{
                    "1" # a unique element in expect.error[[i1]]
                }
            }else{
                paste0("i.list[[", i1, "]][i]")
            }, 
            "]]"
        )
    }
    arg.values <- paste0(arg.values, ")")
    fun.test <- paste0(fun, "(", fun.args, ")")
    fun.test2 <- paste0("paste0('", fun, "(", fun.args2, ")')")
    # plot title for special plot functions
    if(plot.fun == TRUE){
        plot.kind <- "classic"
        if(fun %in% sp.plot.fun){
            plot.kind <- "special"
            if(any(arg %in% "title")){ # this is for the special functions
                tempo.match <- regmatches(x = fun.test, m = regexpr(text = fun.test, pattern = "title = .+[,)]"))
                tempo.match <- substring(tempo.match , 1, nchar(tempo.match) - 1)
                fun.test <- sub(x = fun.test, pattern = tempo.match, replacement = paste0(tempo.match, "\ntempo.title"))
            }else{
                fun.test <- sub(x = fun.test, pattern = ")$", replacement = ", title = tempo.title)")
            }
        }
    }
    # end plot title for special plot functions
    kind <- character()
    problem <- logical()
    expected.error <- logical()
    res <- character()
    count <- 0
    print.count.loop <- 0
    plot.count <- 0
    if(base::length(arg) == 1L){
        data <- data.frame()
    }else{ # base::length(arg) == 0L already tested above
        data <- data.frame(t(vector("character", base::length(arg))), stringsAsFactors = FALSE)[-1, ] # -1 to remove the single row created and to have an empty data frame with base::length(arg) columns
    }
    code <- paste(
        loop.string, '
count <- count + 1
print.count.loop <- print.count.loop + 1
arg.values.print <- eval(parse(text = arg.values)) # recover the list of the i1 compartment
for(j3 in 1:base::length(arg.values.print)){ # WARNING: do not use i1, i2 etc., here because already in loop.string
tempo.capt <- capture.output(tempo.error <- fun_get_message(data =  paste0("paste(arg.values.print[[", j3, "]])"), kind = "error", header = FALSE, env = get(env.name, env = sys.nframe(), inherit = FALSE))) # collapsing arg.values sometimes does not work (with function for instance)
if( ! is.null(tempo.error)){
arg.values.print[[j3]] <- paste0("SPECIAL VALUE OF CLASS ", base::class(arg.values.print[[j3]]), " AND TYPE ", base::typeof(arg.values.print[[j3]]))
Gael's avatar
Gael committed
2233
2234
}
}
2235
2236
2237
2238
2239
data <- rbind(data, as.character(sapply(arg.values.print, FUN = "paste", collapse = " ")), stringsAsFactors = FALSE) # each colum is a test
tempo.capt <- capture.output(tempo.try.error <- fun_get_message(data = eval(parse(text = fun.test2)), kind = "error", header = FALSE, env = get(env.name, env = sys.nframe(), inherit = FALSE))) # data argument needs a character string but eval(parse(text = fun.test2)) provides it (eval parse replace the i1, i2, etc., by the correct values, meaning that only val is required in the env.name environment)
tempo.capt <- capture.output(tempo.try.warning <- fun_get_message(data = eval(parse(text = fun.test2)), kind = "warning", header = FALSE, env = get(env.name, env = sys.nframe(), inherit = FALSE), print.no = TRUE)) # data argument needs a character string but eval(parse(text = fun.test2)) provides it (eval parse replace the i1, i2, etc., by the correct values, meaning that only val is required in the env.name environment)
if( ! is.null(expect.error)){
expected.error <- c(expected.error, eval(parse(text = error.values)))
Gael's avatar
Gael committed
2240
}
2241
2242
2243
2244
if( ! is.null(tempo.try.error)){
kind <- c(kind, "ERROR")
problem <- c(problem, TRUE)
res <- c(res, tempo.try.error)
Gael's avatar
Gael committed
2245
}else{
2246
2247
2248
2249
if( ! is.null(tempo.try.warning)){
kind <- c(kind, "WARNING")
problem <- c(problem, FALSE)
res <- c(res, tempo.try.warning)
Gael's avatar
Gael committed
2250
}else{
2251
2252
2253
kind <- c(kind, "OK")
problem <- c(problem, FALSE)
res <- c(res, "")
Gael's avatar
Gael committed
2254
}
2255
2256
2257
2258
2259
2260
2261
2262
2263
if(plot.fun == TRUE){
invisible(dev.set(window.nb))
plot.count <- plot.count + 1
tempo.title <- paste0("test_", sprintf(paste0("%0", nchar(total.comp.nb), "d"), ifelse(is.null(thread.nb), count, x[count])))
if(plot.kind == "classic"){
eval(parse(text = fun.test))
tempo <- fun_post_plot(corner.text = tempo.title)
}else if(plot.kind == "special"){
eval(parse(text = fun.test))
Gael's avatar
Gael committed
2264
}else{
2265
2266
tempo.cat <- paste0("INTERNAL CODE ERROR 1 IN ", function.name, ": CODE HAS TO BE MODIFIED")
stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
Gael's avatar
Gael committed
2267
2268
2269
}
}
}
2270
2271
2272
2273
2274
2275
2276
if(print.count.loop == print.count){
print.count.loop <- 0
tempo.time <- as.numeric(Sys.time())
tempo.lapse <- round(lubridate::seconds_to_period(tempo.time - ini.time))
final.loop <- (tempo.time - ini.time) / count * ifelse(is.null(thread.nb), total.comp.nb, base::length(x)) # expected duration in seconds # intra nb.compar loop lapse: time lapse / cycles done * cycles remaining
final.exp <- as.POSIXct(final.loop, origin = ini.date)
cat(paste0(ifelse(is.null(thread.nb), "\n", paste0("\nIN PROCESS ", process.id, " | ")), "LOOP ", format(count, big.mark=","), " / ", format(ifelse(is.null(thread.nb), total.comp.nb, base::length(x)), big.mark=","), " | TIME SPENT: ", tempo.lapse, " | EXPECTED END: ", final.exp))
Gael's avatar
Gael committed
2277
}
2278
2279
2280
2281
if(count == ifelse(is.null(thread.nb), total.comp.nb, base::length(x))){
tempo.time <- as.numeric(Sys.time())
tempo.lapse <- round(lubridate::seconds_to_period(tempo.time - ini.time))
cat(paste0(ifelse(is.null(thread.nb), "\nLOOP PROCESS ENDED | ", paste0("\nPROCESS ", process.id, " ENDED | ")), "LOOP ", format(count, big.mark=","), " / ", format(ifelse(is.null(thread.nb), total.comp.nb, base::length(x)), big.mark=","), " | TIME SPENT: ", tempo.lapse, "\n\n"))
Gael's avatar
Gael committed
2282
}
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
', 
end.loop.string
    )
    # end creation of the txt instruction that includes several loops
    if( ! is.null(thread.nb)){
        # list of i numbers that will be split
        i.list <- vector("list", base::length(val)) # positions to split in parallel jobs
        for(i2 in 1:base::length(arg)){
            if(i2 == 1L){
                tempo.divisor <- total.comp.nb / base::length(val[[i2]])
                i.list[[i2]] <- rep(1:base::length(val[[i2]]), each = as.integer(tempo.divisor))
                tempo.multi <- base::length(val[[i2]])
            }else{
                tempo.divisor <- tempo.divisor / base::length(val[[i2]])
                i.list[[i2]] <- rep(rep(1:base::length(val[[i2]]), each = as.integer(tempo.divisor)), time = as.integer(tempo.multi))
                tempo.multi <- tempo.multi * base::length(val[[i2]])
            }
        }
        # end list of i numbers that will be split
        tempo.cat <- paste0("PARALLELIZATION INITIATED AT: ", ini.date)
        cat(paste0("\n", tempo.cat, "\n"))
        tempo.thread.nb = parallel::detectCores(all.tests = FALSE, logical = TRUE) # detect the number of threads
        if(tempo.thread.nb < thread.nb){
            thread.nb <- tempo.thread.nb
        }
        tempo.cat <- paste0("NUMBER OF THREADS USED: ", thread.nb)
        cat(paste0("\n    ", tempo.cat, "\n"))
        Clust <- parallel::makeCluster(thread.nb, outfile = paste0(res.path, "/fun_test_parall_log.txt")) # outfile to print or cat during parallelization (only possible in a file, outfile = "" do not work on windows)
        tempo.cat <- paste0("SPLIT OF TEST NUMBERS IN PARALLELISATION:")
        cat(paste0("\n    ", tempo.cat, "\n"))
        cluster.list <- parallel::clusterSplit(Clust, 1:total.comp.nb) # split according to the number of cluster
        str(cluster.list) # using print(str()) add a NULL below the result
        cat("\n")
        paral.output.list <- parallel::clusterApply( # paral.output.list is a list made of thread.nb compartments, each made of n / thread.nb (mat theo column number) compartment. Each compartment receive the corresponding results of fun_permut(), i.e., data (permuted mat1.perm), warning message, cor (final correlation) and count (number of permutations)
            cl = Clust,
            x = cluster.list,
            function.name = function.name, 
            instruction = instruction, 
            thread.nb = thread.nb, 
            print.count = print.count, 
            total.comp.nb = total.comp.nb, 
            sp.plot.fun = sp.plot.fun,
            i.list = i.list, 
            fun.tested = fun,
            arg.values = arg.values,
            fun.test = fun.test,
            fun.test2 = fun.test2,
            kind = kind,
            problem = problem,
            res = res,
            count = count,
            plot.count = plot.count,
            data = data,
            code = code,
            plot.fun = plot.fun, 
            res.path = res.path, 
            lib.path = lib.path, 
            cute.path = cute.path, 
            fun = function(
                x, 
                function.name, 
                instruction, 
                thread.nb, 
                print.count, 
                total.comp.nb, 
                sp.plot.fun, 
                i.list, 
                fun.tested, 
                arg.values, 
                fun.test, 
                fun.test2, 
                kind, 
                problem, 
                res, 
                count, 
                plot.count, 
                data, 
                code, 
                plot.fun, 
                res.path, 
                lib.path, 
                cute.path
            ){
                # check again: very important because another R
                process.id <- Sys.getpid()
                cat(paste0("\nPROCESS ID ", process.id, " -> TESTS ", x[1], " TO ", x[base::length(x)], "\n"))
                source(cute.path, local = .GlobalEnv)
                fun_pack(req.package = "lubridate", lib.path = lib.path, load = TRUE) # load = TRUE to be sure that functions are present in the environment. And this prevent to use R.lib.path argument of fun_python_pack()
                # end check again: very important because another R
                # plot management
                if(plot.fun == TRUE){
                    pdf(file = paste0(res.path, "/plots_from_fun_test_", x[1], ifelse(base::length(x) == 1L, ".pdf", paste0("-", x[base::length(x)], ".pdf"))))
                }else{
                    pdf(file = NULL) # send plots into a NULL file, no pdf file created
                }
                window.nb <- dev.cur()
                invisible(dev.set(window.nb))
                # end plot management
                # new environment
                ini.date <- Sys.time()
                ini.time <- as.numeric(ini.date) # time of process begin, converted into 
                env.name <- paste0("env", ini.time)
                if(exists(env.name, where = -1)){ # verify if still ok when fun_test() is inside a function
                    tempo.cat <- paste0("ERROR IN ", function.name, ": ENVIRONMENT env.name ALREADY EXISTS. PLEASE RERUN ONCE")
                    stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
                }else{
                    assign(env.name, new.env())
                    assign("val", val, envir = get(env.name, env = sys.nframe(), inherit = FALSE)) # var replaced by val
                }
                # end new environment
                print.count.loop <- 0
                suppressMessages(suppressWarnings(eval(parse(text = code))))
                colnames(data) <- arg
                if( ! is.null(expect.error)){
                    data <- data.frame(data, kind = kind, problem = problem, expected.error = expected.error, message = res, stringsAsFactors = FALSE)
                }else{
                    data <- data.frame(data, kind = kind, problem = problem, message = res, stringsAsFactors = FALSE)
                }
                row.names(data) <- paste0("test_", sprintf(paste0("%0", nchar(total.comp.nb), "d"), x))
                sys.info <- sessionInfo()
                sys.info$loadedOnly <- sys.info$loadedOnly[order(names(sys.info$loadedOnly))] # sort the packages
                invisible(dev.off(window.nb))
                rm(env.name) # optional, because should disappear at the end of the function execution
                # output
                output <- list(fun = fun, instruction = instruction, sys.info = sys.info) # data = data finally removed from the output list, because everything combined in a RData file at the end
                save(output, file = paste0(res.path, "/fun_test_", x[1], ifelse(base::length(x) == 1L, ".RData", paste0("-", x[base::length(x)], ".RData"))))
                if(plot.fun == TRUE & plot.count == 0L){
                    warn.count <- warn.count + 1
                    tempo.warn <- paste0("(", warn.count,") IN PROCESS ", process.id, ": NO PDF PLOT BECAUSE ONLY ERRORS REPORTED")
                    warn <- paste0(ifelse(is.null(warn), tempo.warn, paste0(warn, "\n\n", tempo.warn)))
                    file.remove(paste0(res.path, "/plots_from_fun_test_", x[1], ifelse(base::length(x) == 1L, ".pdf", paste0("-", x[base::length(x)], ".pdf"))))
                }
                table.out <- as.matrix(data)
                # table.out[table.out == ""] <- " " # does not work # because otherwise read.table() converts "" into NA
                table.out <- gsub(table.out, pattern = "\n", replacement = " ")
                write.table(table.out, file = paste0(res.path, "/table_from_fun_test_", x[1], ifelse(base::length(x) == 1L, ".txt", paste0("-", x[base::length(x)], ".txt"))), row.names = TRUE, col.names = NA, append = FALSE, quote = FALSE, sep = "\t", eol = "\n", na = "")
            }
        )
        parallel::stopCluster(Clust)
        # files assembly
        if(base::length(cluster.list) > 1){
            for(i2 in 1:base::length(cluster.list)){
                tempo.file <- paste0(res.path, "/table_from_fun_test_", min(cluster.list[[i2]], na.rm = TRUE), ifelse(base::length(cluster.list[[i2]]) == 1L, ".txt", paste0("-", max(cluster.list[[i2]], na.rm = TRUE), ".txt"))) # txt file
                tempo <- read.table(file = tempo.file, header = TRUE, stringsAsFactors = FALSE, sep = "\t", row.names = 1, comment.char = "", colClasses = "character") #  row.names = 1 (1st column) because now read.table() adds a NA in the header if the header starts by a tabulation, comment.char = "" because colors with #, colClasses = "character" otherwise convert "" (from NULL) into NA
                if(file.exists(paste0(res.path, "/plots_from_fun_test_", min(cluster.list[[i2]], na.rm = TRUE), ifelse(base::length(cluster.list[[i2]]) == 1L, ".pdf", paste0("-", max(cluster.list[[i2]], na.rm = TRUE), ".pdf"))))){
                    tempo.pdf <- paste0(res.path, "/plots_from_fun_test_", min(cluster.list[[i2]], na.rm = TRUE), ifelse(base::length(cluster.list[[i2]]) == 1L, ".pdf", paste0("-", max(cluster.list[[i2]], na.rm = TRUE), ".pdf"))) # pdf file
                }else{
                    tempo.pdf <- NULL
                }
                tempo.rdata <- paste0(res.path, "/fun_test_", min(cluster.list[[i2]], na.rm = TRUE), ifelse(base::length(cluster.list[[i2]]) == 1L, ".RData", paste0("-", max(cluster.list[[i2]], na.rm = TRUE), ".RData"))) # RData file
                if(i2 == 1L){
                    final.file <- tempo
                    final.pdf <- tempo.pdf
                    # new env for RData combining
                    env.name <- paste0("env", ini.time)
                    if(exists(env.name, where = -1)){ # verify if still ok when fun_test() is inside a function
                        tempo.cat <- paste0("ERROR IN ", function.name, ": ENVIRONMENT env.name ALREADY EXISTS. PLEASE RERUN ONCE")
                        stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
                        # end new env for RData combining
                    }else{
                        assign(env.name, new.env())
                        load(tempo.rdata, envir = get(env.name))
                        tempo.rdata1 <- tempo.rdata
                        assign("final.output", get("output", envir = get(env.name)), envir = get(env.name))
                    }
                }else{
                    final.file <- rbind(final.file, tempo, stringsAsFactors = TRUE)
                    final.pdf <- c(final.pdf, tempo.pdf)
                    load(tempo.rdata, envir = get(env.name))
                    if( ! identical(get("final.output", envir = get(env.name))[c("R.version", "locale", "platform")], get("output", envir = get(env.name))[c("R.version", "locale", "platform")])){
                        tempo.cat <- paste0("ERROR IN ", function.name, ": DIFFERENCE BETWEEN OUTPUTS WHILE THEY SHOULD BE IDENTICAL\nPLEASE CHECK\n", tempo.rdata1, "\n", tempo.rdata)
                        stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
                    }else{
                        # add the differences in RData $sysinfo into final.output
                        tempo.base1 <- sort(get("final.output", envir = get(env.name))$sys.info$basePkgs)
                        tempo.base2 <- sort(get("output", envir = get(env.name))$sys.info$basePkgs)
                        tempo.other1 <- names(get("final.output", envir = get(env.name))$sys.info$otherPkgs)
                        tempo.other2 <- names(get("output", envir = get(env.name))$sys.info$otherPkgs)
                        tempo.loaded1 <- names(get("final.output", envir = get(env.name))$sys.info$loadedOnly)
                        tempo.loaded2 <- names(get("output", envir = get(env.name))$sys.info$loadedOnly)
                        assign("final.output", {
                            x <- get("final.output", envir = get(env.name))
                            y <- get("output", envir = get(env.name))
                            x$sys.info$basePkgs <- sort(unique(tempo.base1, tempo.base2))
                            if( ! all(tempo.other2 %in% tempo.other1)){
                                x$sys.info$otherPkgs <- c(x$sys.info$otherPkgs, y$sys.info$otherPkgs[ ! (tempo.other2 %in% tempo.other1)])
                                x$sys.info$otherPkgs <- x$sys.info$otherPkgs[order(names(x$sys.info$otherPkgs))]
                            }
                            if( ! all(tempo.loaded2 %in% tempo.loaded1)){
                                x$sys.info$loadedOnly <- c(x$sys.info$loadedOnly, y$sys.info$loadedOnly[ ! (tempo.loaded2 %in% tempo.loaded1)])
                                x$sys.info$loadedOnly <- x$sys.info$loadedOnly[order(names(x$sys.info$loadedOnly))]
                            }
                            x
                        }, envir = get(env.name))
                        # add the differences in RData $sysinfo into final.output
                    }
                }
                file.remove(c(tempo.file, tempo.rdata))
            }
            # combine pdf and save
            if( ! is.null(final.pdf)){
                pdftools::pdf_combine(
                    input = final.pdf,
                    output = paste0(res.path, "/plots_from_fun_test_1-", total.comp.nb, ".pdf")
                )
                file.remove(final.pdf)
            }
            # end combine pdf and save
            # save RData
            assign("output", c(get("final.output", envir = get(env.name)), data = list(final.file)), envir = get(env.name))
            save(output, file = paste0(res.path, "/fun_test__1-", total.comp.nb, ".RData"), envir = get(env.name))
            rm(env.name) # optional, because should disappear at the end of the function execution
            # end save RData
            # save txt
            write.table(final.file, file = paste0(res.path, "/table_from_fun_test_1-", total.comp.nb, ".txt"), row.names = TRUE, col.names = NA, append = FALSE, quote = FALSE, sep = "\t", eol = "\n", na = "")
            # end save txt
            if( ! is.null(expect.error)){
                final.file <- final.file[ ! final.file$problem == final.file$expected.error, ]
                if(nrow(final.file) == 0L){
                    cat(paste0("NO DISCREPANCY BETWEEN EXPECTED AND OBSERVED ERRORS\n\n"))
                }else{
                    cat(paste0("DISCREPANCIES BETWEEN EXPECTED AND OBSERVED ERRORS (SEE THE discrepancy_table_from_fun_test_1-", total.comp.nb, ".txt FILE)\n\n"))
                    write.table(final.file, file = paste0(res.path, "/discrepancy_table_from_fun_test_1-", total.comp.nb, ".txt"), row.names = TRUE, col.names = NA, append = FALSE, quote = FALSE, sep = "\t", eol = "\n", na = "")
                }
            }
        }
        # end files assembly
    }else{
        # plot management
        if(plot.fun == TRUE){
            pdf(file = paste0(res.path, "/plots_from_fun_test_1", ifelse(total.comp.nb == 1L, ".pdf", paste0("-", total.comp.nb, ".pdf"))))
        }else{
            pdf(file = NULL) # send plots into a NULL file, no pdf file created
        }
        window.nb <- dev.cur()
        invisible(dev.set(window.nb))
        # end plot management
        # new environment
        env.name <- paste0("env", ini.time)
        if(exists(env.name, where = -1)){
            tempo.cat <- paste0("ERROR IN ", function.name, ": ENVIRONMENT env.name ALREADY EXISTS. PLEASE RERUN ONCE")
            stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
        }else{
            assign(env.name, new.env())
            assign("val", val, envir = get(env.name, env = sys.nframe(), inherit = FALSE)) # var replaced by val
        }
        # end new environment
        suppressMessages(suppressWarnings(eval(parse(text = code))))
        colnames(data) <- arg
        expect.data <- data.frame()
        if( ! is.null(expect.error)){
            data <- data.frame(data, kind = kind, problem = problem, expected.error = expected.error, message = res, stringsAsFactors = FALSE)
        }else{
            data <- data.frame(data, kind = kind, problem = problem, message = res, stringsAsFactors = FALSE)
        }
        row.names(data) <- paste0("test_", sprintf(paste0("%0", nchar(total.comp.nb), "d"), 1:total.comp.nb))
        sys.info <- sessionInfo()
        sys.info$loadedOnly <- sys.info$loadedOnly[order(names(sys.info$loadedOnly))] # sort the packages
        invisible(dev.off(window.nb))
        rm(env.name) # optional, because should disappear at the end of the function execution
        # output
        output <- list(fun = fun, instruction = instruction, sys.info = sys.info, data = data)
        if(plot.fun == TRUE & plot.count == 0L){
            warn.count <- warn.count + 1
            tempo.warn <- paste0("(", warn.count,") NO PDF PLOT BECAUSE ONLY ERRORS REPORTED")
            warn <- paste0(ifelse(is.null(warn), tempo.warn, paste0(warn, "\n\n", tempo.warn)))
            file.remove(paste0(res.path, "/plots_from_fun_test_1", ifelse(total.comp.nb == 1L, ".pdf", paste0("-", total.comp.nb, ".pdf"))))
        }
        if( ! is.null(expect.error)){
            expect.data <- output$data[ ! output$data$problem == output$data$expected.error, ]
            if(nrow(expect.data) == 0L){
                cat(paste0("NO DISCREPANCY BETWEEN EXPECTED AND OBSERVED ERRORS\n\n"))
            }else{
                cat(paste0("DISCREPANCIES BETWEEN EXPECTED AND OBSERVED ERRORS (SEE THE ", if(export == TRUE){paste0("discrepancy_table_from_fun_test_1", ifelse(total.comp.nb == 1L, "", paste0("-", total.comp.nb)), ".txt FILE")}else{"$data RESULT"}, ")\n\n"))
                if(export == TRUE){
                    expect.data <- as.matrix(expect.data)
                    expect.data <- gsub(expect.data, pattern = "\n", replacement = "  ")
                    write.table(expect.data, file = paste0(res.path, "/discrepancy_table_from_fun_test_1", ifelse(total.comp.nb == 1L, ".txt", paste0("-", total.comp.nb, ".txt"))), row.names = TRUE, col.names = NA, append = FALSE, quote = FALSE, sep = "\t", eol = "\n", na = "")
                }
            }
        }
        if( ! is.null(warn)){
            base::options(warning.length = 8170)
            on.exit(warning(paste0("FROM ", function.name, ":\n\n", warn), call. = FALSE))
        }
        on.exit(exp = base::options(warning.length = ini.warning.length), add = TRUE)
        if(export == TRUE){
            save(output, file = paste0(res.path, "/fun_test_1", ifelse(total.comp.nb == 1L, ".RData", paste0("-", total.comp.nb, ".RData"))))
            table.out <- as.matrix(output$data)
            table.out <- gsub(table.out, pattern = "\n", replacement = "  ")
            write.table(table.out, file = paste0(res.path, "/table_from_fun_test_1", ifelse(total.comp.nb == 1L, ".txt", paste0("-", total.comp.nb, ".txt"))), row.names = TRUE, col.names = NA, append = FALSE, quote = FALSE, sep = "\t", eol = "\n", na = "")
        }else{
            return(output)
        }
    }
    # after return() ?
    end.date <- Sys.time()
    end.time <- as.numeric(end.date)
    total.lapse <- round(lubridate::seconds_to_period(end.time - ini.time))
    cat(paste0("fun_test JOB END\n\nTIME: ", end.date, "\n\nTOTAL TIME LAPSE: ", total.lapse, "\n\n\n"))
Gael's avatar
Gael committed
2583
2584
2585
}


2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
################ Object modification


######## fun_name_change() #### check a vector of character strings and modify any string if present in another vector


fun_name_change <- function(data1, data2, added.string = "_modif"){
    # AIM
    # this function allow to check if a vector of character strings, like column names of a data frame, has elements present in another vector (vector of reserved words or column names of another data frame before merging)
    # ARGUMENTS
    # data1: vector of character strings to check and modify
    # data2: reference vector of character strings
    # added.string: string added at the end of the modified string in data1 if present in data2
    # RETURN
    # a list containing
    # $data: the modified data1 (in the same order as in the initial data1)
    # $ini: the initial elements before modification. NULL if no modification
    # $post: the modified elements in the same order as in ini. NULL if no modification
    # REQUIRED PACKAGES
    # none
    # REQUIRED FUNCTIONS FROM CUTE_LITTLE_R_FUNCTION
    # fun_check()
    # EXAMPLES
    # obs1 <- c("A", "B", "C", "D") ; obs2 <- c("A", "C") ; fun_name_change(obs1, obs2)
    # obs1 <- c("A", "B", "C", "C_modif1", "D") ; obs2 <- c("A", "A_modif1", "C") ; fun_name_change(obs1, obs2) # the function checks that the new names are neither in obs1 nor in obs2 (increment the number after the added string)
    # DEBUGGING
    # data1 = c("A", "B", "C", "D") ; data2 <- c("A", "C") ; added.string = "_modif" # for function debugging
    # function name
    function.name <- paste0(as.list(match.call(expand.dots = FALSE))[[1]], "()")
    # end function name
    # required function checking
    if(length(utils::find("fun_check", mode = "function")) == 0L){
        tempo.cat <- paste0("ERROR IN ", function.name, ": REQUIRED fun_check() FUNCTION IS MISSING IN THE R ENVIRONMENT")
        stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
    }
    # end required function checking
    # argument checking
    arg.check <- NULL #
    text.check <- NULL #
    checked.arg.names <- NULL # for function debbuging: used by r_debugging_tools
    ee <- expression(arg.check <- c(arg.check, tempo$problem) , text.check <- c(text.check, tempo$text) , checked.arg.names <- c(checked.arg.names, tempo$object.name))
    tempo <- fun_check(data = data1, class = "vector", mode = "character", fun.name = function.name) ; eval(ee)
    tempo <- fun_check(data = data2, class = "vector", mode = "character", fun.name = function.name) ; eval(ee)
    tempo <- fun_check(data = added.string, class = "vector", mode = "character", length = 1, fun.name = function.name) ; eval(ee)
    if(any(arg.check) == TRUE){
        stop(paste0("\n\n================\n\n", paste(text.check[arg.check], collapse = "\n"), "\n\n================\n\n"), call. = FALSE) #
    }
    # source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.7/r_debugging_tools-v1.7.R") ; eval(parse(text = str_basic_arg_check_dev)) ; eval(parse(text = str_arg_check_with_fun_check_dev)) # activate this line and use the function (with no arguments left as NULL) to check arguments status and if they have been checked using fun_check()
    # end argument checking
    # main code
    ini <- NULL
    post <- NULL
    if(any(data1 %in% data2)){
        tempo.names <- data1[data1 %in% data2]
        ini <- NULL
        post <- NULL
        for(i2 in 1:length(tempo.names)){
            count <- 0
            tempo <- tempo.names[i2]
            while(any(tempo %in% data2) | any(tempo %in% data1)){
                count <- count + 1
                tempo <- paste0(tempo.names[i2], "_modif", count)
            }
            data1[data1 %in% tempo.names[i2]] <- paste0(tempo.names[i2], "_modif", count)
            if(count != 0){
                ini <- c(ini, tempo.names[i2])
                post <- c(post, paste0(tempo.names[i2], "_modif", count))
            }
        }
        data <- data1
    }else{
        data <- data1
    }
    output <- list(data = data, ini = ini, post = post)
    return(output)
Gael's avatar
Gael committed
2661
}
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784


######## fun_df_remod() #### remodeling a data frame to have column name as a qualitative values and vice-versa


fun_df_remod <- function(
    data, 
    quanti.col.name = "quanti", 
    quali.col.name = "quali"
){
    # AIM
    # if the data frame is made of numeric columns, a new data frame is created, with the 1st column gathering all the numeric values, and the 2nd column being the name of the columns of the initial data frame. If row names were present in the initial data frame, then a new ini_rowname column is added with the names of the rows
    
    
    # If the data frame is made of one numeric column and one character or factor column, a new data frame is created, with the new columns corresponding to the split numeric values (according to the character column). NA are added a the end of each column to have the same number of rows. BEWARE: in such data frame, rows are not individuals. This means that in the example below, values 10 and 20 are associated on the same row but that means nothing in term of association
    
    
    
    # ARGUMENTS
    # data: data frame to convert
    # quanti.col.name: optional name for the quanti column of the new data frame
    # quali.col.name: optional name for the quali column of the new data frame
    # RETURN
    # the modified data frame
    # REQUIRED PACKAGES
    # none
    # REQUIRED FUNCTIONS FROM CUTE_LITTLE_R_FUNCTION
    # fun_check()
    # EXAMPLES
    # obs <- data.frame(col1 = (1:4)*10, col2 = c("A", "B", "A", "A"), stringsAsFactors = TRUE) ; obs ; fun_df_remod(obs)
    # obs <- data.frame(col1 = (1:4)*10, col2 = 5:8, stringsAsFactors = TRUE) ; obs ; fun_df_remod(obs, quanti.col.name = "quanti", quali.col.name = "quali")
    # obs <- data.frame(col1 = (1:4)*10, col2 = 5:8, stringsAsFactors = TRUE) ; rownames(obs) <- paste0("row", 1:4) ; obs ; fun_df_remod(obs, quanti.col.name = "quanti", quali.col.name = "quali")
    # DEBUGGING
    # data = data.frame(a = 1:3, b = 4:6, stringsAsFactors = TRUE) ; quanti.col.name = "quanti" ; quali.col.name = "quali" # for function debugging
    # data = data.frame(a = 1:3, b = 4:6, c = 11:13, stringsAsFactors = TRUE) ; quanti.col.name = "quanti" ; quali.col.name = "quali" # for function debugging
    # data = data.frame(a = 1:3, b = letters[1:3], stringsAsFactors = TRUE) ; quanti.col.name = "quanti" ; quali.col.name = "quali" # for function debugging
    # data = data.frame(a = 1:3, b = letters[1:3], stringsAsFactors = TRUE) ; quanti.col.name = "TEST" ; quali.col.name = "quali" # for function debugging
    # data = data.frame(b = letters[1:3], a = 1:3, stringsAsFactors = TRUE) ; quanti.col.name = "quanti" ; quali.col.name = "quali" # for function debugging
    # data = data.frame(b = c("e", "e", "h"), a = 1:3, stringsAsFactors = TRUE) ; quanti.col.name = "quanti" ; quali.col.name = "quali" # for function debugging
    # function name
    function.name <- paste0(as.list(match.call(expand.dots = FALSE))[[1]], "()")
    # end function name
    # required function checking
    if(length(utils::find("fun_check", mode = "function")) == 0L){
        tempo.cat <- paste0("ERROR IN ", function.name, ": REQUIRED fun_check() FUNCTION IS MISSING IN THE R ENVIRONMENT")
        stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
    }
    # end required function checking
    # argument checking
    # argument checking without fun_check()
    if( ! any(class(data) %in% "data.frame")){
        tempo.cat <- paste0("ERROR IN ", function.name, ": THE data ARGUMENT MUST BE A DATA FRAME")
        stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
    }
    # end argument checking without fun_check()
    # argument checking with fun_check()
    arg.check <- NULL #
    text.check <- NULL #
    checked.arg.names <- NULL # for function debbuging: used by r_debugging_tools
    ee <- expression(arg.check <- c(arg.check, tempo$problem) , text.check <- c(text.check, tempo$text) , checked.arg.names <- c(checked.arg.names, tempo$object.name))
    tempo <- fun_check(data = quanti.col.name, class = "character", length = 1, fun.name = function.name) ; eval(ee)
    tempo <- fun_check(data = quali.col.name, class = "character", length = 1, fun.name = function.name) ; eval(ee)
    if(any(arg.check) == TRUE){
        stop(paste0("\n\n================\n\n", paste(text.check[arg.check], collapse = "\n"), "\n\n================\n\n"), call. = FALSE) #
    }
    # end argument checking with fun_check()
    # source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.7/r_debugging_tools-v1.7.R") ; eval(parse(text = str_basic_arg_check_dev)) ; eval(parse(text = str_arg_check_with_fun_check_dev)) # activate this line and use the function (with no arguments left as NULL) to check arguments status and if they have been checked using fun_check()
    # end argument checking
    # main code
    tempo.factor <- unlist(lapply(data, class))
    for(i in 1:length(tempo.factor)){ # convert factor columns as character
        if(all(tempo.factor[i] == "factor")){
            data[, i] <- as.character(data[, i])
        }
    }
    tempo.factor <- unlist(lapply(data, mode))
    if(length(data) == 2L){
        if( ! ((base::mode(data[, 1]) == "character" & base::mode(data[, 2]) == "numeric") | base::mode(data[, 2]) == "character" & base::mode(data[, 1]) == "numeric" | base::mode(data[, 2]) == "numeric" & base::mode(data[, 1]) == "numeric") ){
            tempo.cat <- paste0("ERROR IN ", function.name, ": IF data ARGUMENT IS A DATA FRAME MADE OF 2 COLUMNS, EITHER A COLUMN MUST BE NUMERIC AND THE OTHER CHARACTER, OR THE TWO COLUMNS MUST BE NUMERIC")
            stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
        }
        if((base::mode(data[, 1]) == "character" | base::mode(data[, 2]) == "character") & (quanti.col.name != "quanti" | quali.col.name != "quali")){
            tempo.cat <- paste0("ERROR IN ", function.name, ": IMPROPER quanti.col.name OR quali.col.name RESETTINGS. THESE ARGUMENTS ARE RESERVED FOR DATA FRAMES MADE OF n NUMERIC COLUMNS ONLY")
            stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
        }
    }else{
        if( ! all(tempo.factor %in% "numeric")){
            tempo.cat <- paste0("ERROR IN ", function.name, ": IF data ARGUMENT IS A DATA FRAME MADE OF ONE COLUMN, OR MORE THAN 2 COLUMNS, THESE COLUMNS MUST BE NUMERIC")
            stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
        }
    }
    if(( ! any(tempo.factor %in% "character")) & is.null(names(data))){
        tempo.cat <- paste0("ERROR IN ", function.name, ": NUMERIC DATA FRAME in the data ARGUMENT MUST HAVE COLUMN NAMES")
        stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
    }
    if(all(tempo.factor %in% "numeric")){ # transfo 1
        quanti <- NULL
        for(i in 1:length(data)){
            quanti <-c(quanti, data[, i])
        }
        quali <- rep(names(data), each = nrow(data))
        output.data <- data.frame(quanti, quali, stringsAsFactors = TRUE)
        names(output.data) <- c(quanti.col.name, quali.col.name)
        # add the ini_rowname column
        ini.rownames <- rownames(data)
        tempo.data <- data
        rownames(tempo.data) <- NULL
        null.rownames <- (tempo.data)
        if( ! identical(ini.rownames, null.rownames)){