cute_little_R_functions.R 694 KB
Newer Older
Gael  MILLOT's avatar
Gael MILLOT committed
1
2
################################################################
##                                                            ##
Gael  MILLOT's avatar
Gael MILLOT committed
3
##     CUTE LITTLE R FUNCTIONS v6.0.0                         ##
Gael  MILLOT's avatar
Gael MILLOT committed
4
5
6
##                                                            ##
##     Gael A. Millot                                         ##
##                                                            ##
Gael  MILLOT's avatar
Gael MILLOT committed
7
##     Compatible with R v3.5.3                               ##
Gael  MILLOT's avatar
Gael MILLOT committed
8
9
10
11
##                                                            ##
################################################################


12
# https://usethis.r-lib.org/ and usethat also
Gael  MILLOT's avatar
Gael MILLOT committed
13
# BEWARE: do not forget to save the modifications in the .R file (through RSTUDIO for indentation)
Gael  MILLOT's avatar
Gael MILLOT committed
14
# add print warning argument using warning(warnings)
Gael  MILLOT's avatar
Gael MILLOT committed
15
# update graphic examples with good comment, as in barplot
Gael  MILLOT's avatar
Gael MILLOT committed
16
17
# Templates: https://prettydoc.statr.me/themes.html
# https://pkgdown.r-lib.org/
Gael  MILLOT's avatar
Gael MILLOT committed
18
# https://rdrr.io/github/gastonstat/cointoss/
Gael  MILLOT's avatar
Gael MILLOT committed
19
# 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
20
21
22
23

################################ OUTLINE ################################


Gael  MILLOT's avatar
Gael MILLOT committed
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
################ Object analysis    2
######## fun_check() #### check class, type, length, etc., of objects   2
######## fun_info() #### recover object information 8
######## fun_1d_comp() #### comparison of two 1D datasets (vectors, factors, 1D tables) 9
######## fun_2d_comp() #### comparison of two 2D datasets (row & col names, dimensions, etc.)   13
######## fun_2d_head() #### head of the left or right of big 2D objects 20
######## fun_2d_tail() #### tail of the left or right of big 2D objects 21
######## fun_list_comp() #### comparison of two lists   22
################ Object modification    24
######## fun_name_change() #### check a vector of character strings and modify any string if present in another vector  24
######## fun_df_remod() #### remodeling a data frame to have column name as a qualitative values and vice-versa 26
######## fun_merge() #### merge the columns of two 2D objects, by common rows   29
######## fun_round() #### rounding number if decimal present    33
######## fun_mat_rotate() #### 90° clockwise matrix rotation    35
######## fun_mat_num2color() #### convert a numeric matrix into hexadecimal color matrix    35
######## fun_mat_op() #### assemble several matrices with operation 38
######## fun_mat_inv() #### return the inverse of a square matrix   41
######## fun_mat_fill() #### fill the empty half part of a symmetric square matrix  42
######## fun_permut() #### progressively breaks a vector order  45
################ Graphics management    55
######## fun_width() #### window width depending on classes to plot 56
######## fun_open() #### open a GUI or pdf graphic window   57
######## fun_prior_plot() #### set graph param before plotting (erase axes for instance)    60
######## fun_scale() #### select nice label numbers when setting number of ticks on an axis 64
######## fun_post_plot() #### set graph param after plotting (axes redesign for instance)   69
######## fun_close() #### close specific graphic windows    80
################ Standard graphics  81
######## fun_empty_graph() #### text to display for empty graphs    82
################ gg graphics    83
######## fun_gg_palette() #### ggplot2 default color palette    83
######## fun_gg_just() #### ggplot2 justification of the axis labeling, depending on angle  84
######## fun_gg_point_rast() #### ggplot2 raster scatterplot layer  87
######## fun_gg_scatter() #### ggplot2 scatterplot + lines (up to 6 overlays totally)   90
######## fun_gg_bar_mean() #### ggplot2 mean barplot + overlaid dots if required    126
######## fun_gg_boxplot() #### ggplot2 boxplot + background dots if required    161
######## fun_gg_bar_prop() #### ggplot2 proportion barplot  166
######## fun_gg_strip() #### ggplot2 stripchart + mean/median   166
######## fun_gg_violin() #### ggplot2 violins   166
######## fun_gg_line() #### ggplot2 lines + background dots and error bars  166
######## fun_gg_heatmap() #### ggplot2 heatmap + overlaid mask if required  168
######## fun_gg_empty_graph() #### text to display for empty graphs 182
################ Graphic extraction 184
######## fun_trim() #### display values from a quantitative variable and trim according to defined cut-offs 184
######## fun_segmentation() #### segment a dot cloud on a scatterplot and define the dots from another cloud outside the segmentation   192
################ Import 224
######## fun_pack() #### check if R packages are present and import into the working environment    224
######## fun_python_pack() #### check if python packages are present    226
################ Exporting results (text & tables)  227
######## fun_report() #### print string or data object into output file 227
Gael  MILLOT's avatar
Gael MILLOT committed
73
74
75
76
77
78
79
80


################################ FUNCTIONS ################################


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


Gael  MILLOT's avatar
Gael MILLOT committed
81
######## fun_check() #### check class, type, length, etc., of objects
Gael  MILLOT's avatar
Gael MILLOT committed
82
83
84


# Check OK: clear to go Apollo
Gael  MILLOT's avatar
Gael MILLOT committed
85
fun_check <- function(data, data.name = NULL, class = NULL, typeof = NULL, mode = NULL, length = NULL, prop = NULL, double.as.integer.allowed = FALSE, options = NULL, all.options.in.data = FALSE, na.contain = FALSE, neg.values = TRUE, print = TRUE, fun.name = NULL){
Gael  MILLOT's avatar
Gael MILLOT committed
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
    # 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, type, mode or length must be non null
    # if options is non null, then class, type and mode must be NULL, and length can be NULL or specified
    # REQUIRED FUNCTIONS FROM CUTE_LITTLE_R_FUNCTION
    # none
    # ARGUMENTS
    # data: object to test
    # data.name: name of the object to test. If NULL, use the name of the object assigned to the data argument
    # class: one of the class() result or "vector"
    # typeof: one of the typeof() result
    # mode: one of the mode() result (for non vector object)
    # length: length of the object
    # prop: logical, are the numeric values between 0 and 1 (proportion)?
    # double.as.integer.allowed: logical. If TRUE, no error is reported if argument is set to typeof = "integer" or class = "integer", while the reality is typeof = "double" or class = "numeric" but the numbers have a 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
    # options: a vector of possible values for data
    # all.options.in.data: If TRUE, all of the options must be present at least once in data, and nothing else. If FALSE, some of the options must be present in data, and nothing else
    # na.contain: can data contains NA?
    # neg.values: are negative numeric values authorized? BEWARE: only considered if set to FALSE, to check for non negative values when class is set to "numeric", "matrix", "array", "data.frame", "table", or typeof is set to "double", "integer", or mode is set to "numeric"
    # print: print the error message if $problem is TRUE?
    # fun.name: name of the function when fun_check() is used to check its argument. If non NULL, name will be added into the error message returned by fun_check()
    # RETURN
    # a list containing:
    # $problem: logical. Is there any problem detected ?
    # $text: the problem detected
    # $param.name: name of the checked parameter
    # EXAMPLES
    # test <- 1:3 ; fun_check(data = test, data.name = NULL, print = TRUE, options = NULL, all.options.in.data = FALSE, class = NULL, typeof = NULL, mode = NULL, prop = TRUE, double.as.integer.allowed = FALSE, length = NULL)
    # test <- 1:3 ; fun_check(data = test, print = TRUE, class = "numeric", typeof = NULL, double.as.integer.allowed = FALSE)
    # test <- 1:3 ; fun_check(data = test, print = TRUE, class = "vector", mode = "numeric")
    # test <- matrix(1:3) ; fun_check(data = test, print = TRUE, class = "vector", mode = "numeric")
    # DEBUGGING
    # data = expression(TEST) ; data.name = NULL ; class = "vector" ; typeof = NULL ; mode = NULL ; length = 1 ; prop = NULL ; double.as.integer.allowed = FALSE ; options = NULL ; all.options.in.data = FALSE ; na.contain = FALSE ; neg.values = TRUE ; print = TRUE ; fun.name = NULL
    # function name: no used in this function for the error message, to avoid env colliding
    # argument checking
    if( ! is.null(data.name)){
        if( ! (length(data.name) == 1 & class(data.name) == "character")){
            tempo.cat <- paste0("\n\n================\n\nERROR IN fun_check(): data.name ARGUMENT MUST BE A SINGLE CHARACTER ELEMENT AND NOT ", paste(data.name, collapse = " "), "\n\n================\n\n")
            stop(tempo.cat)
        }
    }
    if(is.null(options) & is.null(class) & is.null(typeof) & is.null(mode) & is.null(prop) & is.null(length)){
        tempo.cat <- paste0("\n\n================\n\nERROR IN fun_check(): AT LEAST ONE OF THE options, class, typeof, mode, prop, OR length ARGUMENT MUST BE SPECIFIED\n\n================\n\n")
        stop(tempo.cat)
    }
    if( ! is.null(options) & ( ! is.null(class) | ! is.null(typeof) | ! is.null(mode) | ! is.null(prop))){
        tempo.cat <- paste0("\n\n================\n\nERROR IN fun_check(): THE class, typeof, mode AND prop ARGUMENTS MUST BE NULL IF THE option ARGUMENT IS SPECIFIED\nTHE option ARGUMENT MUST BE NULL IF THE class AND/OR typeof AND/OR mode AND/OR prop ARGUMENT IS SPECIFIED\n\n================\n\n")
        stop(tempo.cat)
    }
    if( ! (all(class(neg.values) == "logical") & length(neg.values) == 1 & any(is.na(neg.values)) != TRUE)){
        tempo.cat <- paste0("\n\n================\n\nERROR IN fun_check(): THE neg.values ARGUMENT MUST BE TRUE OR FALSE ONLY\n\n================\n\n")
        stop(tempo.cat)
    }
    if(neg.values == FALSE & is.null(class) & is.null(typeof) & is.null(mode)){
        tempo.cat <- paste0("\n\n================\n\nERROR IN fun_check(): THE neg.values ARGUMENT CANNOT BE SWITCHED TO FALSE IF class, typeof AND mode ARGUMENTS ARE NULL\n\n================\n\n")
        stop(tempo.cat)
    }
    if( ! is.null(class)){
        if( ! all(class %in% c("vector", "logical", "integer", "numeric", "complex", "character", "matrix", "array", "data.frame", "list", "factor", "table", "expression", "name", "symbol", "function", "uneval") & any(is.na(class)) != TRUE)){ # not length == 1 here because ordered factors are class "factor" "ordered" (length == 2)
            tempo.cat <- paste0("\n\n================\n\nERROR IN fun_check(): 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\" \n\n================\n\n")
            stop(tempo.cat)
        }
        if(neg.values == FALSE & ! any(class %in% c("vector", "numeric", "integer", "matrix", "array", "data.frame", "table"))){
            tempo.cat <- paste0("\n\n================\n\nERROR IN fun_check(): class ARGUMENT CANNOT BE OTHER THAN \"vector\", \"numeric\", \"integer\", \"matrix\", \"array\", \"data.frame\", \"table\" IF neg.values ARGUMENT IS SWITCHED TO FALSE\n\n================\n\n")
            stop(tempo.cat)
        }
    }
    if( ! is.null(typeof)){
        if( ! (all(typeof %in% c("logical", "integer", "double", "complex", "character", "list", "expression", "name", "symbol", "closure", "special", "builtin")) & length(typeof) == 1 & any(is.na(typeof)) != TRUE)){
            tempo.cat <- paste0("\n\n================\n\nERROR IN fun_check(): typeof ARGUMENT MUST BE ONE OF THESE VALUE:\n\"logical\", \"integer\", \"double\", \"complex\", \"character\", \"list\", \"expression\", \"name\", \"symbol\", \"closure\", \"special\", \"builtin\" \n\n================\n\n")
            stop(tempo.cat)
        }
        if(neg.values == FALSE & ! typeof %in% c("double", "integer")){
            tempo.cat <- paste0("\n\n================\n\nERROR IN fun_check(): typeof ARGUMENT CANNOT BE OTHER THAN \"double\" OR \"integer\" IF neg.values ARGUMENT IS SWITCHED TO FALSE\n\n================\n\n")
            stop(tempo.cat)
        }
    }
    if( ! is.null(mode)){
        if( ! (all(mode %in% c("logical", "numeric", "complex", "character", "list", "expression", "name", "symbol", "function")) & length(mode) == 1 & any(is.na(mode)) != TRUE)){
            tempo.cat <- paste0("\n\n================\n\nERROR IN fun_check(): mode ARGUMENT MUST BE ONE OF THESE VALUE:\n\"logical\", \"numeric\", \"complex\", \"character\", \"list\", \"expression\", \"name\", \"symbol\", \"function\"\n\n================\n\n")
            stop(tempo.cat)
        }
        if(neg.values == FALSE & mode != "numeric"){
            tempo.cat <- paste0("\n\n================\n\nERROR IN fun_check(): mode ARGUMENT CANNOT BE OTHER THAN \"numeric\" IF neg.values ARGUMENT IS SWITCHED TO FALSE\n\n================\n\n")
            stop(tempo.cat)
        }
    }
    if( ! is.null(length)){
        if( ! (is.numeric(length) & length(length) == 1 & ! grepl(length, pattern = "\\.") & any(is.na(length)) != TRUE)){
            tempo.cat <- paste0("\n\n================\n\nERROR IN fun_check(): length ARGUMENT MUST BE A SINGLE INTEGER VALUE\n\n================\n\n")
            stop(tempo.cat)
        }
    }
    if( ! is.null(prop)){
        if( ! (is.logical(prop) | length(prop) == 1 & any(is.na(prop)) != TRUE)){
            tempo.cat <- paste0("\n\n================\n\nERROR IN fun_check(): prop ARGUMENT MUST BE TRUE OR FALSE ONLY\n\n================\n\n")
            stop(tempo.cat)
        }else if(prop == TRUE){
            if( ! is.null(class)){
                if( ! any(class %in% c("vector", "numeric", "integer", "matrix", "array", "data.frame", "table"))){
                    tempo.cat <- paste0("\n\n================\n\nERROR IN fun_check(): class ARGUMENT CANNOT BE OTHER THAN \"vector\", \"numeric\", \"integer\", \"matrix\", \"array\", \"data.frame\", \"table\" IF prop ARGUMENT IS TRUE\n\n================\n\n")
                    stop(tempo.cat)
                }
            }
            if( ! is.null(mode)){
                if(mode != "numeric"){
                    tempo.cat <- paste0("\n\n================\n\nERROR IN fun_check(): mode ARGUMENT CANNOT BE OTHER THAN \"numeric\" IF prop ARGUMENT IS TRUE\n\n================\n\n")
                    stop(tempo.cat)
                }
            }
            if( ! is.null(typeof)){
                if(typeof != "double"){
                    tempo.cat <- paste0("\n\n================\n\nERROR IN fun_check(): typeof ARGUMENT CANNOT BE OTHER THAN \"double\" IF prop ARGUMENT IS TRUE\n\n================\n\n")
                    stop(tempo.cat)
                }
            }
        }
    }
    if( ! (all(class(double.as.integer.allowed) == "logical") & length(double.as.integer.allowed) == 1 & any(is.na(double.as.integer.allowed)) != TRUE)){
        tempo.cat <- paste0("\n\n================\n\nERROR IN fun_check(): THE double.as.integer.allowed ARGUMENT MUST BE TRUE OR FALSE ONLY: ", paste(double.as.integer.allowed, collapse = " "), "\n\n================\n\n")
        stop(tempo.cat)
    }
    if( ! (is.logical(all.options.in.data) & length(all.options.in.data) == 1 & any(is.na(all.options.in.data)) != TRUE)){
        tempo.cat <- paste0("\n\n================\n\nERROR IN fun_check(): all.options.in.data ARGUMENT MUST BE A SINGLE LOGICAL VALUE (TRUE OR FALSE ONLY): ", paste(all.options.in.data, collapse = " "), "\n\n================\n\n")
        stop(tempo.cat)
    }
    if( ! (all(class(na.contain) == "logical") & length(na.contain) == 1 & any(is.na(na.contain)) != TRUE)){
        tempo.cat <- paste0("\n\n================\n\nERROR IN fun_check(): THE na.contain ARGUMENT MUST BE TRUE OR FALSE ONLY: ", paste(na.contain, collapse = " "), "\n\n================\n\n")
        stop(tempo.cat)
    }
    if( ! (all(class(print) == "logical") & length(print) == 1 & any(is.na(print)) != TRUE)){
        tempo.cat <- paste0("\n\n================\n\nERROR IN fun_check(): THE print ARGUMENT MUST BE TRUE OR FALSE ONLY: ", paste(print, collapse = " "), "\n\n================\n\n")
        stop(tempo.cat)
    }
    if( ! is.null(fun.name)){
        if( ! (class(fun.name) == "character" & length(fun.name) == 1)){
            tempo.cat <- paste0("\n\n================\n\nERROR IN fun_check(): THE fun.name ARGUMENT MUST BE A CHARACTER VECTOR OF LENGTH 1: ", paste(fun.name, collapse = " "), "\n\n================\n\n")
            stop(tempo.cat)
        }
    }
    # source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.2/r_debugging_tools-v1.2.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
    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, " PARAMETER")
    if( ! is.null(options)){
        text <- ""
        if( ! all(data %in% options)){
            problem <- TRUE
            text <- paste0(ifelse(is.null(fun.name), "ERROR", paste0("ERROR IN ", fun.name)), ": THE ", data.name, " PARAMETER 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)){
                problem <- TRUE
                if(text == ""){
                    text <- paste0(ifelse(is.null(fun.name), "ERROR", paste0("ERROR IN ", fun.name)), ": THE ", data.name, " PARAMETER MUST BE SOME OF THESE OPTIONS: ", paste(options, collapse = " "), "\nTHE PROBLEMATIC ELEMENTS OF ", data.name, " ARE: ", unique(data[ ! (data %in% options)]))
                }else{
                    text <- paste0(text, "\n", ifelse(is.null(fun.name), "ERROR", paste0("ERROR IN ", fun.name)), ": THE ", data.name, " PARAMETER MUST BE SOME OF THESE OPTIONS: ", paste(options, collapse = " "), "\nTHE PROBLEMATIC ELEMENTS OF ", data.name, " ARE: ", unique(data[ ! (data %in% options)]))
                }
            }
        }
        if( ! is.null(length)){
            if(length(data) != length){
                problem <- TRUE
                if(text == ""){
                    text <- paste0(ifelse(is.null(fun.name), "ERROR", paste0("ERROR IN ", fun.name)), ": THE LENGTH OF ", data.name, " MUST BE ", length, " AND NOT ", length(data))
                }else{
                    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 ", length(data))
                }
            }
        }
        if(text == ""){
            text <- paste0(ifelse(is.null(fun.name), "", paste0("IN ", fun.name, ": ")), "NO PROBLEM DETECTED FOR THE ", data.name, " PARAMETER")
        }
    }
    arg.names <- c("class", "typeof", "mode", "length")
    if(is.null(options)){
        for(i2 in 1:length(arg.names)){
            if( ! is.null(get(arg.names[i2]))){
                # script to execute
                tempo.script <- '
Gael  MILLOT's avatar
Gael MILLOT committed
272
problem <- TRUE ;
Gael  MILLOT's avatar
Gael MILLOT committed
273
274
if(identical(text, paste0(ifelse(is.null(fun.name), "", paste0("IN ", fun.name, ": ")), "NO PROBLEM DETECTED FOR THE ", data.name, " PARAMETER"))){
text <- paste0(ifelse(is.null(fun.name), "ERROR", paste0("ERROR IN ", fun.name)), ": THE ", data.name, " PARAMETER MUST BE ") ;
Gael  MILLOT's avatar
Gael MILLOT committed
275
276
277
278
279
}else{
text <- paste0(text, " AND "); 
}
text <- paste0(text, toupper(arg.names[i2]), " ", get(arg.names[i2]))
'
Gael  MILLOT's avatar
Gael MILLOT committed
280
281
282
283
284
285
286
287
288
289
290
291
292
            # end script to execute
            if(typeof(data) == "double" & double.as.integer.allowed == TRUE & ((arg.names[i2] == "class" & get(arg.names[i2]) == "integer") | (arg.names[i2] == "typeof" & get(arg.names[i2]) == "integer"))){
                if(! all(data%%1 == 0)){ # to check integers (use %%, meaning the remaining of a division): see the precedent line
                    eval(parse(text = tempo.script)) # execute tempo.script
                }
            }else if(get(arg.names[i2]) != "vector" & eval(parse(text = paste0(arg.names[i2], "(data)"))) != get(arg.names[i2])){
                eval(parse(text = tempo.script)) # execute tempo.script
            }else if(arg.names[i2] == "class" & get(arg.names[i2]) == "vector" & ! (class(data) == "numeric" | class(data) == "integer" | class(data) == "character" | class(data) == "logical")){
                eval(parse(text = tempo.script)) # execute tempo.script
            }
            }
        }
    }
Gael  MILLOT's avatar
Gael MILLOT committed
293
if( ! is.null(prop)){
Gael  MILLOT's avatar
Gael MILLOT committed
294
295
296
297
298
299
300
301
302
303
304
    if(prop == TRUE){
        if(any(data < 0 | data > 1, na.rm = TRUE)){
            problem <- TRUE
            if(identical(text, paste0(ifelse(is.null(fun.name), "", paste0("IN ", fun.name, ": ")), "NO PROBLEM DETECTED FOR THE ", data.name, " PARAMETER"))){
                text <- paste0(ifelse(is.null(fun.name), "ERROR", paste0("ERROR IN ", fun.name)), ": ")
            }else{
                text <- paste0(text, " AND ")
            }
            text <- paste0(text, "THE ", data.name, " PARAMETER MUST BE DECIMAL VALUES BETWEEN 0 AND 1")
        }
    }
Gael  MILLOT's avatar
Gael MILLOT committed
305
}
306
if(all(class(data) %in% "expression")){
Gael  MILLOT's avatar
Gael MILLOT committed
307
    data <- as.character(data) # to evaluate the presence of NA
308
}
Gael  MILLOT's avatar
Gael MILLOT committed
309
if(na.contain == FALSE & any(is.na(data)) == TRUE){
Gael  MILLOT's avatar
Gael MILLOT committed
310
311
312
313
314
315
316
    problem <- TRUE
    if(identical(text, paste0(ifelse(is.null(fun.name), "", paste0("IN ", fun.name, ": ")), "NO PROBLEM DETECTED FOR THE ", data.name, " PARAMETER"))){
        text <- paste0(ifelse(is.null(fun.name), "ERROR", paste0("ERROR IN ", fun.name)), ": ")
    }else{
        text <- paste0(text, " AND ")
    }
    text <- paste0(text, "THE ", data.name, " PARAMETER CONTAINS NA WHILE NOT AUTHORIZED (na.contain ARGUMENT SET TO FALSE)")
Gael  MILLOT's avatar
Gael MILLOT committed
317
318
}
if(neg.values == FALSE){
Gael  MILLOT's avatar
Gael MILLOT committed
319
320
321
322
323
324
325
326
327
    if(any(data < 0, na.rm = TRUE)){
        problem <- TRUE
        if(identical(text, paste0(ifelse(is.null(fun.name), "", paste0("IN ", fun.name, ": ")), "NO PROBLEM DETECTED FOR THE ", data.name, " PARAMETER"))){
            text <- paste0(ifelse(is.null(fun.name), "ERROR", paste0("ERROR IN ", fun.name)), ": ")
        }else{
            text <- paste0(text, " AND ")
        }
        text <- paste0(text, "THE ", data.name, " PARAMETER MUST BE NON NEGATIVE NUMERIC VALUES")
    }
Gael  MILLOT's avatar
Gael MILLOT committed
328
329
}
if(print == TRUE & problem == TRUE){
Gael  MILLOT's avatar
Gael MILLOT committed
330
    cat(paste0("\n\n================\n\n", text, "\n\n================\n\n"))
Gael  MILLOT's avatar
Gael MILLOT committed
331
332
333
334
}
output <- list(problem = problem, text = text, param.name = data.name)
return(output)
}
Gael  MILLOT's avatar
Gael MILLOT committed
335
336


Gael  MILLOT's avatar
Gael MILLOT committed
337
######## fun_info() #### recover object information
Gael  MILLOT's avatar
Gael MILLOT committed
338
339
340


# Check OK: clear to go Apollo
Gael  MILLOT's avatar
Gael MILLOT committed
341
fun_info <- function(data){
Gael  MILLOT's avatar
Gael MILLOT committed
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
    # AIM
    # provide a full description of an object
    # REQUIRED FUNCTIONS FROM CUTE_LITTLE_R_FUNCTION
    # none
    # ARGUMENTS
    # data: object to test
    # RETURN
    # a list containing the info
    # please, use names(fun_info()) and remove what can be too big for easy analysis
    # EXAMPLES
    # fun_info(data = 1:3)
    # fun_info(data.frame(a = 1:2, b = ordered(factor(c("A", "B")))))
    # fun_info(list(a = 1:3, b = ordered(factor(c("A", "B")))))
    # DEBUGGING
    # data = NULL # for function debugging
    # data = 1:3 # for function debugging
    # data = matrix(1:3) # for function debugging
    # data = data.frame(a = 1:2, b = c("A", "B")) # for function debugging
    # data = factor(c("b", "a")) # for function debugging
    # data = ordered(factor(c("b", "a"))) # for function debugging
    # data = list(a = 1:3, b = factor(c("A", "B"))) # for function debugging
    # data = list(a = 1:3, b = ordered(factor(c("A", "B")))) # for function debugging
    # function name: no need because no check and no message
    # argument checking
    # source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.2/r_debugging_tools-v1.2.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
    data.name <- deparse(substitute(data))
    output <- list("NAME" = data.name)
    tempo <- list("CLASS" = class(data))
    output <- c(output, tempo)
    tempo <- list("TYPE" = typeof(data))
    output <- c(output, tempo)
    tempo <- list("HEAD" = head(data))
    output <- c(output, tempo)
    if( ! is.null(data)){
        tempo <- list("TAIL" = tail(data))
        output <- c(output, tempo)
        if( ! is.null(dim(data))){
            tempo <- list("DIMENSION" = dim(data))
            names(tempo[[1]]) <- c("NROW", "NCOL")
            output <- c(output, tempo)
        }
        tempo <- list("SUMMARY" = summary(data))
        output <- c(output, tempo)
    }
    if(all(class(data) == "data.frame" | class(data) == "matrix")){
        tempo <- list("ROW_NAMES" = dimnames(data)[[1]])
        output <- c(output, tempo)
        tempo <- list("COLUM_NAMES" = dimnames(data)[[2]])
        output <- c(output, tempo)
    }
    if(all(class(data) == "data.frame")){
        tempo <- list("STRUCTURE" = ls.str(data))
        output <- c(output, tempo)
        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") 
            tempo.class <- sapply(data, FUN = "class")
            if(any(unlist(tempo.class) %in% "ordered")){
                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")){
        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") 
            tempo.class <- sapply(data, FUN = "class")
            if(any(unlist(tempo.class) %in% "ordered")){
                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)
    }
    return(output)
Gael  MILLOT's avatar
Gael MILLOT committed
425
426
427
}


Gael  MILLOT's avatar
Gael MILLOT committed
428
######## fun_1d_comp() #### comparison of two 1D datasets (vectors, factors, 1D tables)
Gael  MILLOT's avatar
Gael MILLOT committed
429
430
431


# Check OK: clear to go Apollo
Gael  MILLOT's avatar
Gael MILLOT committed
432
fun_1d_comp <- function(data1, data2){
Gael  MILLOT's avatar
Gael MILLOT committed
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
    # AIM
    # compare two 1D datasets (vector of factor or 1D table) 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)
    # REQUIRED FUNCTIONS FROM CUTE_LITTLE_R_FUNCTION
    # none
    # ARGUMENTS
    # data1: vector or factor or 1D table
    # data2: vector or factor or 1D table
    # 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 ?
    # $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 elements names identical in data1
    # $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
    # $same.element.pos2: position, in data2, of the elements identical in data1
    # $common.elements: common elements between data1 and data2. NULL if no common elements
    # $identical.object: logical. Are objects identical (kind of object, element names and content)?
    # $identical.content: logical. Are content objects identical (identical elements excluding kind of object and element names)?
    # EXAMPLES
    # obs1 = 1:5 ; obs2 = 1:5 ; names(obs1) <- LETTERS[1:5] ; names(obs2) <- LETTERS[1:5] ; fun_1d_comp(obs1, obs2)
    # obs1 = 1:5 ; obs2 = 1:5 ; names(obs1) <- LETTERS[1:5] ; fun_1d_comp(obs1, obs2)
    # obs1 = 1:5 ; obs2 = 3:6 ; names(obs1) <- LETTERS[1:5] ; names(obs2) <- LETTERS[1:4] ; fun_1d_comp(obs1, obs2)
    # obs1 = factor(LETTERS[1:5]) ; obs2 = factor(LETTERS[1:5]) ; fun_1d_comp(obs1, obs2)
    # obs1 = factor(LETTERS[1:5]) ; obs2 = factor(LETTERS[10:11]) ; fun_1d_comp(obs1, obs2)
    # obs1 = factor(LETTERS[1:5]) ; obs2 = factor(LETTERS[4:7]) ; fun_1d_comp(obs1, obs2)
    # obs1 = 1:5 ; obs2 = factor(LETTERS[1:5]) ; fun_1d_comp(obs1, obs2)
    # obs1 = 1:5 ; obs2 = 1.1:6.1 ; fun_1d_comp(obs1, obs2)
    # obs1 = as.table(1:5); obs2 = as.table(1:5) ; fun_1d_comp(obs1, obs2)
    # obs1 = as.table(1:5); obs2 = 1:5 ; fun_1d_comp(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("\n\n================\n\nERROR IN ", function.name, ": THE data1 ARGUMENT MUST BE A NON NULL VECTOR, FACTOR OR 1D TABLE\n\n================\n\n")
        stop(tempo.cat)
    }else if(all(class(data1) %in% "table")){
        if(length(dim(data1)) > 1){
            tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": THE data1 ARGUMENT MUST BE A 1D TABLE\n\n================\n\n")
            stop(tempo.cat)
        }
    }
    if( ! any(class(data2) %in% c("logical", "integer", "numeric", "character", "factor", "table"))){
        tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": THE data2 ARGUMENT MUST BE A NON NULL VECTOR, FACTOR OR 1D TABLE\n\n================\n\n")
        stop(tempo.cat)
    }else if(all(class(data2) %in% "table")){
        if(length(dim(data2)) > 1){
            tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": THE data2 ARGUMENT MUST BE A 1D TABLE\n\n================\n\n")
            stop(tempo.cat)
        }
    }
    # source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.2/r_debugging_tools-v1.2.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.length <- NULL
    length <- NULL
    same.levels <- NULL
    levels <- NULL
    any.id.levels <- NULL
    same.levels.pos1 <- NULL
    same.levels.pos2 <- NULL
    common.levels <- NULL
    same.name <- NULL
    name <- NULL
    any.id.name <- NULL
    same.name.pos1 <- NULL
    same.name.pos2 <- NULL
    common.names <- NULL
    any.id.element <- NULL
    same.element.pos1 <- NULL
    same.element.pos2 <- NULL
    common.elements <- NULL
    identical.object <- NULL
    identical.content <- NULL
    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
        identical.object <- TRUE
        identical.content <- TRUE
    }else{
        identical.object <- FALSE
        if( ! identical(class(data1), class(data2))){
            same.class <- FALSE
        }else{
            same.class <- TRUE
            class <- class(data1)
        }
        if( ! identical(length(data1), length(data2))){
            same.length<- FALSE
        }else{
            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 <- FALSE
            }else{
                same.levels <- TRUE
                levels <- levels(data1)
            }
            any.id.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 <- 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))
            }
            if(any.id.name == TRUE){
                common.names <- unique(c(names(data1)[same.name.pos1], names(data2)[same.name.pos2]))
            }
        }
        any.id.element <- FALSE
        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(same.length == TRUE & ! all(is.null(same.element.pos1), is.null(same.element.pos2))){
            names(same.element.pos1) <- NULL
            names(same.element.pos2) <- NULL
            if(identical(same.element.pos1, same.element.pos2)){
                identical.content <- TRUE
            }else{
                identical.content <- FALSE
            }
        }else{
            identical.content <- FALSE
        }
    }
    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, identical.object = identical.object, identical.content = identical.content)
    return(output)
Gael  MILLOT's avatar
Gael MILLOT committed
641
642
643
}


Gael  MILLOT's avatar
Gael MILLOT committed
644
######## fun_2d_comp() #### comparison of two 2D datasets (row & col names, dimensions, etc.)
Gael  MILLOT's avatar
Gael MILLOT committed
645
646
647


# Check OK: clear to go Apollo
Gael  MILLOT's avatar
Gael MILLOT committed
648
fun_2d_comp <- function(data1, data2){
Gael  MILLOT's avatar
Gael MILLOT committed
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
    # 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
    # REQUIRED FUNCTIONS FROM CUTE_LITTLE_R_FUNCTION
    # none
    # 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) ?
    # $same.row.pos1: position, in data1, of the rows identical in data2 (not considering row names)
    # $same.row.pos2: position, in data2, of the rows identical in data1 (not considering row names)
    # $any.id.col: logical. is there identical columns (not considering column names)?
    # $same.col.pos1: position in data1 of the cols identical in data2 (not considering column names)
    # $same.col.pos2: position in data2 of the cols identical in data1 (not considering column names)
    # $identical.object: logical. Are objects identical (including row & column names)?
    # $identical.content: logical. Are content objects identical (identical excluding row & column names)?
    # 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]))) ; obs1 ; obs2 ; fun_2d_comp(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_2d_comp(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_2d_comp(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_2d_comp(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]) ; data2 = data.frame(A = 1:3, B= letters[1:3]) # 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]))) # 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]) # 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("matrix", "data.frame", "table"))){
        tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": THE data1 ARGUMENT MUST BE A MATRIX, DATA FRAME OR TABLE\n\n================\n\n")
        stop(tempo.cat)
    }
    if( ! any(class(data2) %in% c("matrix", "data.frame", "table"))){
        tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": THE data2 ARGUMENT MUST BE A MATRIX, DATA FRAME OR TABLE\n\n================\n\n")
        stop(tempo.cat)
    }
    # source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.2/r_debugging_tools-v1.2.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("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)) == 1){
            tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": THE data1 ARGUMENT IS A 1D TABLE. USE THE info_1D_dataset_fun FUNCTION\n\n================\n\n")
            stop(tempo.cat)
        }
        if(all(class(data2) == "table") & length(dim(data2)) == 1){
            tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": THE data2 ARGUMENT IS A 1D TABLE. USE THE info_1D_dataset_fun FUNCTION\n\n================\n\n")
            stop(tempo.cat)
        }
        if( ! identical(class(data1), class(data2))){
            same.class <- FALSE
        }else if( ! any(class(data1) %in% c("matrix", "data.frame", "table"))){
            tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": THE data1 AND data2 ARGUMENTS MUST BE EITHER MATRIX, DATA FRAME OR TABLE\n\n================\n\n")
            stop(tempo.cat)
        }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) == "matrix")){
            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) == "matrix")){
            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
            same.row.pos1 <- which(c(as.data.frame(t(data1), stringsAsFactors = FALSE)) %in% c(as.data.frame(t(data2), stringsAsFactors = FALSE)))
            same.row.pos2 <- which(c(as.data.frame(t(data2), stringsAsFactors = FALSE)) %in% c(as.data.frame(t(data1), stringsAsFactors = FALSE)))
            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{
            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
            same.col.pos1 <- which(c(data1) %in% c(data2))
            same.col.pos2 <- which(c(data2) %in% c(data1))
            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{
            any.id.col <- FALSE
            # same.col.pos1 and 2 remain NULL
        }
        if(same.dim == TRUE & ! all(is.null(same.row.pos1), is.null(same.row.pos2), is.null(same.col.pos1), is.null(same.col.pos2))){ # same.dim == TRUE means that same.row.nb == TRUE and same.col.nb == TRUE, meaning that row.nb != NULL and col.nb != NULL. Thus, no need to include these checkings
            if(identical(same.row.pos1, 1:row.nb) & identical(same.row.pos2, 1:row.nb) & identical(same.col.pos1, 1:col.nb) & identical(same.col.pos2, 1:col.nb)){
                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  MILLOT's avatar
Gael MILLOT committed
948
949
950
}


Gael  MILLOT's avatar
Gael MILLOT committed
951
######## fun_2d_head() #### head of the left or right of big 2D objects
Gael  MILLOT's avatar
Gael MILLOT committed
952
953
954


# Check OK: clear to go Apollo
Gael  MILLOT's avatar
Gael MILLOT committed
955
fun_2d_head <- function(data1, n = 10, side = "l"){
Gael  MILLOT's avatar
Gael MILLOT committed
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
    # AIM
    # display the head of the left or right of big 2D objects
    # REQUIRED FUNCTIONS FROM CUTE_LITTLE_R_FUNCTION
    # fun_check()
    # ARGUMENTS
    # data1: matrix, data frame or table
    # n: 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
    # RETURN
    # the head
    # EXAMPLES
    # obs1 = matrix(1:30, ncol = 5, dimnames = list(letters[1:6], LETTERS[1:5])) ; obs1 ; fun_2d_head(obs1, 3)
    # obs1 = matrix(1:30, ncol = 5, dimnames = list(letters[1:6], LETTERS[1:5])) ; obs1 ; fun_2d_head(obs1, 3, "right")
    # DEBUGGING
    # data1 = matrix(1:30, ncol = 5) # for function 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(find("fun_check", mode = "function")) == 0){
        tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": REQUIRED fun_check() FUNCTION IS MISSING IN THE R ENVIRONMENT\n\n================\n\n")
        stop(tempo.cat)
    }
    # end required function checking
    # argument checking
    # argument checking without fun_check()
    if( ! any(class(data1) %in% c("matrix", "data.frame", "table"))){
        tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": THE data1 ARGUMENT MUST BE A MATRIX, DATA FRAME OR TABLE\n\n================\n\n")
        stop(tempo.cat)
    }
    # end argument checking without fun_check()
    # argument checking with fun_check()
    arg.check <- NULL # for function debbuging
    checked.arg.names <- NULL # for function debbuging: used by r_debugging_tools
    ee <- expression(arg.check <- c(arg.check, tempo$problem) , checked.arg.names <- c(checked.arg.names, tempo$param.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() # nothing else because print = TRUE by default in fun_check()
    }
    # end argument checking with fun_check()
    # source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.2/r_debugging_tools-v1.2.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
    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])
Gael  MILLOT's avatar
Gael MILLOT committed
1010
1011
1012
}


Gael  MILLOT's avatar
Gael MILLOT committed
1013
######## fun_2d_tail() #### tail of the left or right of big 2D objects
Gael  MILLOT's avatar
Gael MILLOT committed
1014
1015
1016


# Check OK: clear to go Apollo
Gael  MILLOT's avatar
Gael MILLOT committed
1017
fun_2d_tail <- function(data1, n = 10, side = "l"){
Gael  MILLOT's avatar
Gael MILLOT committed
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
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
    # AIM
    # display the tail of the left or right of big 2D objects
    # REQUIRED FUNCTIONS FROM CUTE_LITTLE_R_FUNCTION
    # fun_check()
    # ARGUMENTS
    # data1: matrix, data frame or table
    # n: 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
    # RETURN
    # the tail
    # EXAMPLES
    # obs1 = matrix(1:30, ncol = 5, dimnames = list(letters[1:6], LETTERS[1:5])) ; obs1 ; fun_2d_tail(obs1, 3)
    # obs1 = matrix(1:30, ncol = 5, dimnames = list(letters[1:6], LETTERS[1:5])) ; obs1 ; fun_2d_tail(obs1, 3, "r")
    # DEBUGGING
    # data1 = matrix(1:10, ncol = 5) # for function 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(find("fun_check", mode = "function")) == 0){
        tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": REQUIRED fun_check() FUNCTION IS MISSING IN THE R ENVIRONMENT\n\n================\n\n")
        stop(tempo.cat)
    }
    # end required function checking
    # argument checking
    # argument checking without fun_check()
    if( ! any(class(data1) %in% c("matrix", "data.frame", "table"))){
        tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": THE data1 ARGUMENT MUST BE A MATRIX, DATA FRAME OR TABLE\n\n================\n\n")
        stop(tempo.cat)
    }
    # end argument checking without fun_check()
    # argument checking with fun_check()
    arg.check <- NULL # for function debbuging
    checked.arg.names <- NULL # for function debbuging: used by r_debugging_tools
    ee <- expression(arg.check <- c(arg.check, tempo$problem) , checked.arg.names <- c(checked.arg.names, tempo$param.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() # nothing else because print = TRUE by default in fun_check()
    }
    # end argument checking with fun_check()
    # source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.2/r_debugging_tools-v1.2.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
    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  MILLOT's avatar
Gael MILLOT committed
1072
1073
1074
}


Gael  MILLOT's avatar
Gael MILLOT committed
1075
1076
1077
1078
1079
######## fun_list_comp() #### comparison of two lists


# Check OK: clear to go Apollo
fun_list_comp <- function(data1, data2){
Gael  MILLOT's avatar
Gael MILLOT committed
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
1109
1110
1111
1112
1113
1114
1115
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
    # AIM
    # compare two lists. Check and report in a list if the 2 datasets have:
    # same length
    # common names
    # common compartments
    # REQUIRED FUNCTIONS FROM CUTE_LITTLE_R_FUNCTION
    # none
    # 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)?
    # 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_list_comp(obs1, obs2)
    # obs1 = list(1:5, LETTERS[1:2]) ; obs2 = list(a = 1:5, b = LETTERS[1:2]) ; fun_list_comp(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_list_comp(obs1, obs2)
    # obs1 = list(b = 1:5, c = LETTERS[1:2]) ; obs2 = list(LETTERS[5:9], matrix(1:6), 1:5) ; fun_list_comp(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("\n\n================\n\nERROR IN ", function.name, ": THE data1 ARGUMENT MUST BE A LIST\n\n================\n\n")
        stop(tempo.cat)
    }
    if( ! any(class(data2) %in% "list")){
        tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": THE data2 ARGUMENT MUST BE A LIST\n\n================\n\n")
        stop(tempo.cat)
    }
    # source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.2/r_debugging_tools-v1.2.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  MILLOT's avatar
Gael MILLOT committed
1202
1203
1204
1205
1206
1207
}


################ Object modification


Gael  MILLOT's avatar
Gael MILLOT committed
1208
1209
1210
1211
1212
######## fun_name_change() #### check a vector of character strings and modify any string if present in another vector


# Check OK: clear to go Apollo
fun_name_change <- function(data1, data2, added.string = "_modif"){
Gael  MILLOT's avatar
Gael MILLOT committed
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
    # 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)
    # REQUIRED FUNCTIONS FROM CUTE_LITTLE_R_FUNCTION
    # fun_check()
    # 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 or unmodified 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
    # 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(find("fun_check", mode = "function")) == 0){
        tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": REQUIRED fun_check() FUNCTION IS MISSING IN THE R ENVIRONMENT\n\n================\n\n")
        stop(tempo.cat)
    }
    # end required function checking
    # argument checking
    arg.check <- NULL # for function debbuging
    checked.arg.names <- NULL # for function debbuging: used by r_debugging_tools
    ee <- expression(arg.check <- c(arg.check, tempo$problem) , checked.arg.names <- c(checked.arg.names, tempo$param.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() # nothing else because print = TRUE by default in fun_check()
    }
    # source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.2/r_debugging_tools-v1.2.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(i3 in 1:length(tempo.names)){
            count <- 0
            tempo <- tempo.names[i3]
            while(any(tempo %in% data2) | any(tempo %in% data1)){
                count <- count + 1
                tempo <- paste0(tempo.names[i3], "_modif", count)
            }
            data1[data1 %in% tempo.names[i3]] <- paste0(tempo.names[i3], "_modif", count)
            if(count != 0){
                ini <- c(ini, tempo.names[i3])
                post <- c(post, paste0(tempo.names[i3], "_modif", count))
            }
        }
        data <- data1
    }else{
        data <- data1
    }
    output <- list(data = data, ini = ini, post = post)
    return(output)
Gael  MILLOT's avatar
Gael MILLOT committed
1278
1279
1280
}


Gael  MILLOT's avatar
Gael MILLOT committed
1281
######## fun_df_remod() #### remodeling a data frame to have column name as a qualitative values and vice-versa
Gael  MILLOT's avatar
Gael MILLOT committed
1282
1283
1284


# Check OK: clear to go Apollo
Gael  MILLOT's avatar
Gael MILLOT committed
1285
fun_df_remod <- function(data, quanti.col.name = "quanti", quali.col.name = "quali"){
Gael  MILLOT's avatar
Gael MILLOT committed
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
1327
1328
1329
1330
1331
1332
1333
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
    # 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
    
    
    
    # REQUIRED FUNCTIONS FROM CUTE_LITTLE_R_FUNCTION
    # fun_check()
    # 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
    # EXAMPLES
    # obs <- data.frame(col1 = (1:4)*10, col2 = c("A", "B", "A", "A")) ; obs ; fun_df_remod(obs)
    # obs <- data.frame(col1 = (1:4)*10, col2 = 5:8) ; obs ; fun_df_remod(obs, quanti.col.name = "quanti", quali.col.name = "quali")
    # obs <- data.frame(col1 = (1:4)*10, col2 = 5:8) ; 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) ; quanti.col.name = "quanti" ; quali.col.name = "quali" # for function debugging
    # data = data.frame(a = 1:3, b = 4:6, c = 11:13) ; quanti.col.name = "quanti" ; quali.col.name = "quali" # for function debugging
    # data = data.frame(a = 1:3, b = letters[1:3]) ; quanti.col.name = "quanti" ; quali.col.name = "quali" # for function debugging
    # data = data.frame(a = 1:3, b = letters[1:3]) ; quanti.col.name = "TEST" ; quali.col.name = "quali" # for function debugging
    # data = data.frame(b = letters[1:3], a = 1:3) ; quanti.col.name = "quanti" ; quali.col.name = "quali" # for function debugging
    # data = data.frame(b = c("e", "e", "h"), a = 1:3) ; 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(find("fun_check", mode = "function")) == 0){
        tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": REQUIRED fun_check() FUNCTION IS MISSING IN THE R ENVIRONMENT\n\n================\n\n")
        stop(tempo.cat)
    }
    # end required function checking
    # argument checking
    # argument checking without fun_check()
    if( ! any(class(data) %in% "data.frame")){
        tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": THE data ARGUMENT MUST BE A DATA FRAME\n\n================\n\n")
        stop(tempo.cat)
    }
    # end argument checking without fun_check()
    # argument checking with fun_check()
    arg.check <- NULL # for function debbuging
    checked.arg.names <- NULL # for function debbuging: used by r_debugging_tools
    ee <- expression(arg.check <- c(arg.check, tempo$problem) , checked.arg.names <- c(checked.arg.names, tempo$param.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() # nothing else because print = TRUE by default in fun_check()
    }
    # end argument checking with fun_check()
    # source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.2/r_debugging_tools-v1.2.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) == 2){
        if( ! ((mode(data[, 1]) == "character" & mode(data[, 2]) == "numeric") | mode(data[, 2]) == "character" & mode(data[, 1]) == "numeric" | mode(data[, 2]) == "numeric" & mode(data[, 1]) == "numeric") ){
            tempo.cat <- paste0("\n\n================\n\nERROR 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\n\n================\n\n")
            stop(tempo.cat)
        }
        if((mode(data[, 1]) == "character" | mode(data[, 2]) == "character") & (quanti.col.name != "quanti" | quali.col.name != "quali")){
            tempo.cat <- paste0("\n\n================\n\nERROR 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\n\n================\n\n")
            stop(tempo.cat)
        }
    }else{
        if( ! all(tempo.factor %in% "numeric")){
            tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": IF data ARGUMENT IS A DATA FRAME MADE OF ONE COLUMN, OR MORE THAN 2 COLUMNS, THESE COLUMNS MUST BE NUMERIC\n\n================\n\n")
            stop(tempo.cat)
        }
    }
    if(( ! any(tempo.factor %in% "character")) & is.null(names(data))){
        tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": NUMERIC DATA FRAME in the data ARGUMENT MUST HAVE COLUMN NAMES\n\n================\n\n")
        stop()
    }
    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)
        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)){
            ini_rowname <- rep(ini.rownames, times = ncol(data))
            output.data <- cbind(output.data, ini_rowname)
        }
    }else{ # transfo 2
        if(class(data[, 1]) == "character"){
            data <- cbind(data[2], data[1])
        }
        nc.max <- max(table(data[, 2])) # effectif maximum des classes
        nb.na <- nc.max - table(data[,2]) # nombre de NA à ajouter pour réaliser la data frame
        tempo<-split(data[, 1], data[, 2])
        for(i in 1:length(tempo)){tempo[[i]] <- append(tempo[[i]], rep(NA, nb.na[i]))} # des NA doivent être ajoutés lorsque les effectifs sont différents entre les classes. C'est uniquement pour que chaque colonne ait le même nombre de lignes
        output.data<-data.frame(tempo)
    }
    return(output.data)
Gael  MILLOT's avatar
Gael MILLOT committed
1396
1397
1398
}


Gael  MILLOT's avatar
Gael MILLOT committed
1399
######## fun_merge() #### merge the columns of two 2D objects, by common rows
Gael  MILLOT's avatar
Gael MILLOT committed
1400
1401


Gael  MILLOT's avatar
Gael MILLOT committed
1402
fun_merge <- function(data1, data2, name1, name2, factor.as = "numeric", warn.print = FALSE){
Gael  MILLOT's avatar
Gael MILLOT committed
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
    # AIM
    # merge the columns of 2 data frames or 2 matrices or 2 tables, by associating the rows according to 1 or several common colums that must be strictly similar between the 2 objects
    # contrary to the classical merge() function of R, fun_merge() orders the rows of the 2 objects according to the common columns, and merge only and only if the ordered common columns are strictly identical. Otherwise return an error
    # keep row names of data1 in the merged object if they exist. Do not consider row names of data2
    # keep the intial row order of data1 after merging
    # BEWARE:
    # REQUIRED PACKAGES
    # none
    # REQUIRED FUNCTIONS FROM CUTE_LITTLE_R_FUNCTION
    # fun_2d_comp()
    # fun_check()
    # ARGUMENTS
    # data1: matrix or data frame or table
    # data2: same class of object as data1 (data frame for data1 data frame, matrix for data1 matrix and table for data1 table) with same number of rows as in data1
    # name1: either a vector of character strings or a vector of integer. If character strings, they must be the name of the columns in data1 that are common to the columns in data2. If integers, they must be the column numbers in data1 that are common to column numbers in data2. name1 can be strings and name2 (below) integers, and vice-versa. BEWARE: order of the elements in data1 are important as ordering is according to the first element, then the second, etc.
    # name2: as in name1 but for data2. Order in name2 is not important as order in name1 is used for the ordering
    # factor.as: either "numeric" (sort factors according to levels order, i.e., class number) or "character" (sort factors according to alphabetical order)
    # warn.print: logical. Print warnings at the end of the execution? No print if no warning messages
    # RETURN
    # a list containing:
    # $data: the merged data frame or matrix or table
    # $warnings: the warning messages. Use cat() for proper display. NULL if no warning
    # 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]))) ; obs1 ; obs2 ; fun_2d_comp(obs1, obs2)
    # DEBUGGING
    # data1 = matrix(1.0001:21, ncol = 4) ; dimnames(data1) <- list(LETTERS[1:5], letters[1:4]); data2 = matrix(1.0001:31, ncol = 6) ; dimnames(data2) <- list(NULL, c("a", "aa", "c", "d", "aaa", "aaaa")) ; set.seed(1) ; data2[, "c"] <- sample(data2[, "c"]) ; data2[, "d"] <- sample(data2[, "d"]) ; set.seed(NULL) ; data1 ; data2 ; name1 = c("c", "d") ; name2 = c("d", "c") ; factor.as = "numeric" # for function debugging
    # function name
    function.name <- paste0(as.list(match.call(expand.dots=FALSE))[[1]], "()")
    # end function name
    # required function checking
    if(length(find("fun_check", mode = "function")) == 0){
        tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": REQUIRED fun_check() FUNCTION IS MISSING IN THE R ENVIRONMENT\n\n================\n\n")
        stop(tempo.cat)
    }
    # end required function checking
    # argument checking using fun_check()
    arg.check <- NULL # for function debbuging
    checked.arg.names <- NULL # for function debbuging
    ee <- expression(arg.check <- c(arg.check, tempo$problem) , checked.arg.names <- c(checked.arg.names, tempo$param.name))
    tempo1 <- fun_check(data = data1, class = "matrix", print = FALSE)
    tempo2 <- fun_check(data = data1, class = "data.frame", print = FALSE)
    tempo3 <- fun_check(data = data1, class = "table", print = FALSE)
    if(tempo1$problem == TRUE & tempo2$problem == TRUE & tempo3$problem == TRUE){
        tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ":\ndata1 ARGUMENT MUST BE A 2D OBJECT (MATRIX, DATA FRAME OR TABLE)\nHERE IT IS: ", paste(class(data1), collapse = " "), "\n\n================\n\n") #
        cat(tempo.cat)
        arg.check <- c(arg.check, TRUE)
    }
    tempo1 <- fun_check(data = data2, class = "matrix", print = FALSE)
    tempo2 <- fun_check(data = data2, class = "data.frame", print = FALSE)
    tempo3 <- fun_check(data = data2, class = "table", print = FALSE)
    if(tempo1$problem == TRUE & tempo2$problem == TRUE & tempo3$problem == TRUE){
        tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ":\ndata2 ARGUMENT MUST BE A 2D OBJECT (MATRIX, DATA FRAME OR TABLE)\nHERE IT IS: ", paste(class(data2), collapse = " "), "\n\n================\n\n") #
        cat(tempo.cat)
        arg.check <- c(arg.check, TRUE)
    }
    if( ! identical(class(data1), class(data2))){
        tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ":\ndata1 and data2 ARGUMENTS MUST BE A 2D OBJECT (MATRIX, DATA FRAME OR TABLE) OF SAME CLASS\nHERE IT IS RESPECTIVELY: ", paste(class(data1), collapse = " "), " AND ", paste(class(data2), collapse = " "), "\n\n================\n\n") #
        cat(tempo.cat)
        arg.check <- c(arg.check, TRUE)
    }
    tempo1 <- fun_check(data = name1, class = "vector", typeof = "integer", , double.as.integer.allowed = TRUE, print = FALSE)
    tempo2 <- fun_check(data = name1, class = "vector", typeof = "character", , print = FALSE)
    if(tempo1$problem == TRUE & tempo2$problem == TRUE){
        tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ":\nname1 ARGUMENT MUST BE A UNIQUE CHARACTER STRING OR INTEGER\nHERE IT IS: ", paste(name1, collapse = " "), "\n\n================\n\n") #
        cat(tempo.cat)
        arg.check <- c(arg.check, TRUE)
    }
    tempo1 <- fun_check(data = name2, class = "vector", typeof = "integer", , double.as.integer.allowed = TRUE, print = FALSE)
    tempo2 <- fun_check(data = name2, class = "vector", typeof = "character", , print = FALSE)
    if(tempo1$problem == TRUE & tempo2$problem == TRUE){
        tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ":\nname2 ARGUMENT MUST BE A UNIQUE CHARACTER STRING OR INTEGER\nHERE IT IS: ", paste(name2, collapse = " "), "\n\n================\n\n") #
        cat(tempo.cat)
        arg.check <- c(arg.check, TRUE)
    }
    tempo <- fun_check(data = factor.as, options = c("numeric", "character"), length = 1, fun.name = function.name) ; eval(ee)
    tempo <- fun_check(data = warn.print, class = "vector", mode = "logical", length = 1, fun.name = function.name) ; eval(ee)
    if(any(arg.check) == TRUE){
        stop() # nothing else because print = TRUE by default in fun_check()
    }
    # source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.2/r_debugging_tools-v1.2.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 using fun_check()
    # other argument checking
    # column existence
    if(mode(name1) == "character"){
        if( ! all(name1 %in% colnames(data1))){
            tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ":\nTHE CHARACTER STRINGS IN name1 ARGUMENT ARE NOT ALL COLUMN NAMES OF data1:\n", paste(name1, collapse = " "), "\n", colnames(data1), "\n\n================\n\n") #
            stop(tempo.cat)
        }
    }else if(mode(name1) == "numeric"){
        if( ! all((name1 > ncol(data1) & name1 <= 0))){
            tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ":\nINTEGERS IN name1 ARGUMENT ARE NOT ALL COLUMN NUMBERS OF data1:\n", paste(name1, collapse = " "), "\n1:", ncol(data1), "\n\n================\n\n") #
            stop(tempo.cat)
        }
    }else{
        tempo.cat <- paste0("\n\n============\n\nERROR IN ", function.name, ": CODE INCONSISTENCY 1\n\n============\n\n")
        stop(tempo.cat)
    }
    if(mode(name2) == "character"){
        if( ! all(name2 %in% colnames(data2))){
            tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ":\nTHE CHARACTER STRINGS IN name2 ARGUMENT ARE NOT ALL COLUMN NAMES OF data2:\n", paste(name2, collapse = " "), "\n", colnames(data2), "\n\n================\n\n") #
            stop(tempo.cat)
        }
    }else if(mode(name2) == "numeric"){
        if( ! all((name2 > ncol(data2) & name2 <= 0))){
            tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ":\nINTEGERS IN name2 ARGUMENT ARE NOT ALL COLUMN NUMBERS OF data2:\n", paste(name2, collapse = " "), "\n1:", ncol(data2), "\n\n================\n\n") #
            stop(tempo.cat)
        }
    }else{
        tempo.cat <- paste0("\n\n============\n\nERROR IN ", function.name, ": CODE INCONSISTENCY 2\n\n============\n\n")
        stop(tempo.cat)
    }
    if(length(name1) != length(name2)){
        tempo.cat <- paste0("\n\n============\n\nERROR IN ", function.name, ":\nLENGTH OF name1 ARGUMENT (", length(name1), ") IS NOT THE SAME AS LENGTH OF name2 ARGUMENT (", length(name2), "):\n", paste(name1, collapse = " "), "\n", paste(name2, collapse = " "), "\n\n============\n\n")
        stop(tempo.cat)
    }
    # end column existence
    # end other argument checking
    # main code
    # definition of set1 and set2: common columns
    set1 <- data1[, name1, drop = FALSE] # set1 will be the reference for merging, drop = FALSE to keep the 2D structure
    if(any(apply(set1, 2, FUN = "%in%", "factor"))){
        if(factor.as == "numeric"){
            set1[, apply(set1, 2, FUN = "%in%", "factor")] <- as.numeric(set1[, apply(set1, 2, FUN = "%in%", "factor")])
        }
    }
    set2 <- data2[, name2, drop = FALSE] # set2 will be the reference for merging, drop = FALSE to keep the 2D structure
    if(any(apply(set2, 2, FUN = "%in%", "factor"))){
        if(factor.as == "numeric"){
            set2[, apply(set2, 2, FUN = "%in%", "factor")] <- as.numeric(set2[, apply(set2, 2, FUN = "%in%", "factor")])
        }
    }
    # end definition of set1 and set2: common columns
    # conversion as character to avoid floating point problems
    options.ini <- options()$digits
    options(digits = 22)
    set1 <- as.matrix(set1)
    set2 <- as.matrix(set2)
    mode(set1) <- "character"
    mode(set2) <- "character"
    options(digits = options.ini)
    # end conversion as character to avoid floating point problems
    # recovering initial order of set1
    ini.set1.order <- eval(parse(text = paste("order(", paste("set1[, ", 1:ncol(set1), "]", sep = "", collapse = ", "), ")")))
    set1 <- set1[ini.set1.order, ]
    ini.set2.order <- eval(parse(text = paste("order(", paste("set2[, ", 1:ncol(set2), "]", sep = "", collapse = ", "), ")")))
    set2 <- set2[ini.set2.order, ]
    # end recovering initial order of set1
    # check non identical columns
    if(length(name1) > 1){
        for(i2 in 1:(length(name1) - 1)){
            for(i3 in (i2 + 1):length(name1)){
                if(identical(set1[, i2], set1[, i3])){
                    tempo.cat <- paste0("\n\n============\n\nERROR IN ", function.name, ":\nCOLUMN ", i2, " OF data1 CORRESPONDING TO ELEMENT ", name1[i2], " OF name1 ARGUMENT IS IDENTICAL TO COLUMN ", i3, " OF data1 CORRESPONDING TO ELEMENT ", name1[i3], " OF name1 ARGUMENT\n\n============\n\n")
                    stop(tempo.cat)
                }
            }
        }
    }
    if(length(name2) > 1){
        for(i2 in 1:(length(name2) - 1)){
            for(i3 in (i2 + 1):length(name2)){
                if(identical(set2[, i2], set2[, i3])){
                    tempo.cat <- paste0("\n\n============\n\nERROR IN ", function.name, ":\nCOLUMN ", i2, " OF data2 CORRESPONDING TO ELEMENT ", name2[i2], " OF name2 ARGUMENT IS IDENTICAL TO COLUMN ", i3, " OF data2 CORRESPONDING TO ELEMENT ", name2[i3], " OF name2 ARGUMENT\n\n============\n\n")
                    stop(tempo.cat)
                }
            }
        }
    }
    # end check non identical columns
    # warning duplicates
    # repositioning of the column in set2 as in set1 by comparing the two sorted column
    #deal with identical col names when merging -> .x for data1, .y for data2
    
    
    if(warn.print == TRUE & ! is.null(warning)){
        warning(warning)
    }
    # output <- list()
    return(output)
Gael  MILLOT's avatar
Gael MILLOT committed
1582
1583
1584
}


Gael  MILLOT's avatar
Gael MILLOT committed
1585
######## fun_round() #### rounding number if decimal present
Gael  MILLOT's avatar
Gael MILLOT committed
1586
1587
1588


# Check OK: clear to go Apollo
Gael  MILLOT's avatar
Gael MILLOT committed
1589
fun_round <- function(data, dec.nb = 2, after.lead.zero = TRUE){
Gael  MILLOT's avatar
Gael MILLOT committed
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
    # AIM
    # round a vector of values, if decimal, with the desired number of decimal digits after the decimal leading zeros
    # WARNINGS
    # Work well with numbers as character strings, but not always with numerical numbers because of the floating point
    # Numeric values are really truncated from a part of their decimal digits, whatever options(digits) settings
    # See ?.Machine or https://stackoverflow.com/questions/5173692/how-to-return-number-of-decimal-places-in-r, with the interexting formula: abs(x - round(x)) > .Machine$double.eps^0.5
    # ARGUMENTS
    # data: a vector of numbers (numeric or character mode)
    # dec.nb: number of required decimal digits
    # after.lead.zero: logical. If FALSE, rounding is performed for all the decimal numbers, whatever the leading zeros (e.g., 0.123 -> 0.12 and 0.00128 -> 0.00). If TRUE, dec.nb are taken after the leading zeros (e.g., 0.123 -> 0.12 and 0.00128 -> 0.0013)
    # REQUIRED FUNCTIONS FROM CUTE_LITTLE_R_FUNCTION
    # fun_check()
    # RETURN
    # the modified vector
    # EXAMPLES
    # ini.options <- options()$digits ; options(digits = 8) ; cat(fun_round(data = c(NA, 10, 100.001, 333.0001254, 12312.1235), dec.nb = 2, after.lead.zero = FALSE), "\n\n") ; options(digits = ini.options)
    # ini.options <- options()$digits ; options(digits = 8) ; cat(fun_round(data = c(NA, 10, 100.001, 333.0001254, 12312.1235), dec.nb = 2, after.lead.zero = TRUE), "\n\n") ; options(digits = ini.options)
    # ini.options <- options()$digits ; options(digits = 8) ; cat(fun_round(data = c(NA, "10", "100.001", "333.0001254", "12312.1235"), dec.nb = 2, after.lead.zero = FALSE), "\n\n") ; options(digits = ini.options)
    # ini.options <- options()$digits ; options(digits = 8) ; cat(fun_round(data = c(NA, "10", "100.001", "333.0001254", "12312.1235"), dec.nb = 2, after.lead.zero = TRUE), "\n\n") ; options(digits = ini.options)
    # DEBUGGING
    # data = data = c(10, 100.001, 333.0001254, 12312.1235) ; dec.nb = 2 ; after.lead.zero = FALSE # # for function debugging
    # data = data = c("10", "100.001", "333.0001254", "12312.1235") ; dec.nb = 2 ; after.lead.zero = TRUE # # for function debugging
    # function name
    function.name <- paste0(as.list(match.call(expand.dots=FALSE))[[1]], "()")
    # end function name
    # required function checking
    if(length(find("fun_check", mode = "function")) == 0){
        tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": REQUIRED fun_check() FUNCTION IS MISSING IN THE R ENVIRONMENT\n\n================\n\n")
        stop(tempo.cat)
    }
    # end required function checking
    # argument checking
    # argument checking without fun_check()
    if( ! (all(typeof(data) == "character") | all(typeof(data) == "double") | all(typeof(data) == "integer"))){
        tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": data ARGUMENT MUST BE A VECTOR OF NUMBERS (IN NUMERIC OR CHARACTER MODE)\n\n================\n\n")
        stop(tempo.cat)
    }
    # end argument checking without fun_check()
    # argument checking with fun_check()
    arg.check <- NULL # for function debbuging
    checked.arg.names <- NULL # for function debbuging: used by r_debugging_tools
    ee <- expression(arg.check <- c(arg.check, tempo$problem) , checked.arg.names <- c(checked.arg.names, tempo$param.name))
    tempo <- fun_check(data = data, class = "vector", na.contain = TRUE, fun.name = function.name) ; eval(ee)
    tempo <- fun_check(data = dec.nb, class = "vector", typeof = "integer", length = 1, double.as.integer.allowed = TRUE, neg.values = FALSE, fun.name = function.name) ; eval(ee)
    tempo <- fun_check(data = after.lead.zero, class = "logical", length = 1, fun.name = function.name) ; eval(ee)
    if(any(arg.check) == TRUE){
        stop() # nothing else because print = TRUE by default in fun_check()
    }
    # end argument checking with fun_check()
    # source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.2/r_debugging_tools-v1.2.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 <- grepl(x = data, pattern = "\\.") # detection of decimal numbers
    ini.mode <- mode(data)
    data <- as.character(data) # to really truncate decimal digits
    for(i in 1:length(data)){ # scan all the numbers of the vector
        if(tempo[i] == TRUE){ # means decimal number
            if(after.lead.zero == TRUE){
                zero.pos <- unlist(gregexpr(text=data[i], pattern = 0)) # recover all the position of the zeros in the number. -1 if no zeros (do not record the leading and trailing zeros)
            }else{
                zero.pos <- -1 # -1 as if no zero
            }
            dot.pos <- unlist(gregexpr(text=data[i], pattern = "\\.")) # recover all the position of the zeros in the number
            digit.pos <- unlist(gregexpr(text=data[i], pattern = "[[:digit:]]")) # recover all the position of the digits in the number
            dec.pos <- digit.pos[digit.pos > dot.pos]
            count <- 0
            while((dot.pos + count + 1) %in% zero.pos & (dot.pos + count + 1) <= max(dec.pos) & (count + dec.nb) < length(dec.pos)){ # count the number of leading zeros in the decimal part
                count <- count + 1
            }
            data[i] <- formatC(as.numeric(data[i]), digits = (count + dec.nb), format = "f")
        }
    }
    if(ini.mode != "character"){
        data <- as.numeric(data)
    }
    return(data)
Gael  MILLOT's avatar
Gael MILLOT committed
1666
1667
1668
}


1669
######## fun_mat_rotate() #### 90° clockwise matrix rotation
Gael  MILLOT's avatar
Gael MILLOT committed
1670
1671
1672


# Check OK: clear to go Apollo
1673
fun_mat_rotate <- function(data){
Gael  MILLOT's avatar
Gael MILLOT committed
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
1703
1704
1705
1706
1707
1708
1709
1710
    # AIM
    # 90° clockwise matrix rotation
    # applied twice, the function provide the mirror matrix, according to vertical and horizontal symmetry
    # REQUIRED FUNCTIONS FROM CUTE_LITTLE_R_FUNCTION
    # fun_check()
    # ARGUMENTS
    # data: matrix (matrix class)
    # RETURN
    # the modified matrix
    # EXAMPLES
    # obs <- matrix(1:10, ncol = 1) ; obs ; fun_mat_rotate(obs)
    # obs <- matrix(LETTERS[1:10], ncol = 5) ; obs ; fun_mat_rotate(obs)
    # DEBUGGING
    # data = matrix(1:10, ncol = 1)
    # function name
    function.name <- paste0(as.list(match.call(expand.dots=FALSE))[[1]], "()")
    # end function name
    # required function checking
    if(length(find("fun_check", mode = "function")) == 0){
        tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": REQUIRED fun_check() FUNCTION IS MISSING IN THE R ENVIRONMENT\n\n================\n\n")
        stop(tempo.cat)
    }
    # end required function checking
    # argument checking
    arg.check <- NULL # for function debbuging
    checked.arg.names <- NULL # for function debbuging: used by r_debugging_tools
    ee <- expression(arg.check <- c(arg.check, tempo$problem) , checked.arg.names <- c(checked.arg.names, tempo$param.name))
    tempo <- fun_check(data = data, class = "matrix", fun.name = function.name) ; eval(ee)
    if(any(arg.check) == TRUE){
        stop() # nothing else because print = TRUE by default in fun_check()
    }
    # source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.2/r_debugging_tools-v1.2.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
    for (i in 1:ncol(data)){data[,i] <- rev(data[,i])}
    data <- t(data)
    return(data)
Gael  MILLOT's avatar
Gael MILLOT committed
1711
1712
1713
}


1714
######## fun_mat_num2color() #### convert a numeric matrix into hexadecimal color matrix
Gael  MILLOT's avatar
Gael MILLOT committed
1715
1716
1717


# Check OK: clear to go Apollo
1718
fun_mat_num2color <- function(mat1, mat.hsv.h = TRUE, notch = 1, s = 1, v = 1, forced.color = NULL){
Gael  MILLOT's avatar
Gael MILLOT committed
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
1834
1835
1836
1837
    # AIM
    # convert a matrix made of numbers into a hexadecimal matrix for rgb colorization
    # REQUIRED FUNCTIONS FROM CUTE_LITTLE_R_FUNCTION
    # fun_check()
    # ARGUMENTS:
    # mat1: matrix 1 of non negative numerical values that has to be colored (matrix class). NA allowed
    # mat.hsv.h: logical. Is mat1 the h of hsv colors ? (if TRUE, mat1 must be between zero and 1)
    # notch: single value between 0 and 1 to shift the successive colors on the hsv circle by + notch
    # s: s argument of hsv(). Must be between 0 and 1
    # v: v argument of hsv(). Must be between 0 and 1
    # forced.color: Must be NULL or hexadecimal color code or name given by colors(). The first minimal values of mat1 will be these colors. All the color of mat1 can be forced using this argument
    # RETURN
    # a list containing:
    # $mat1.name: name of mat1
    # $colored.mat: colors of mat1 in hexa
    # $problem: logical. Is any colors of forced.color overlap the colors designed by the function. NULL if forced.color = NULL
    # $text.problem: text when overlapping colors. NULL if forced.color = NULL or problem == FALSE
    # EXAMPLES
    # mat1 = matrix(c(1,1,1,2,1,5,9,NA), ncol = 2) ; dimnames(mat1) <- list(LETTERS[1:4], letters[1:2]) ; fun_mat_num2color(mat1, mat.hsv.h = FALSE, notch = 1, s = 1, v = 1, forced.color = NULL)
    # DEBUGGING
    # mat1 = matrix(c(1,1,1,2,1,5,9,NA), ncol = 2) ; dimnames(mat1) <- list(LETTERS[1:4], letters[1:2]); mat.hsv.h = FALSE ; notch = 1 ; s = 1 ; v = 1 ; forced.color = c(hsv(1,1,1), hsv(0,0,0)) # for function debugging
    # function name
    function.name <- paste0(as.list(match.call(expand.dots=FALSE))[[1]], "()")
    # end function name
    # required function checking
    if(length(find("fun_check", mode = "function")) == 0){
        tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": REQUIRED fun_check() FUNCTION IS MISSING IN THE R ENVIRONMENT\n\n================\n\n")
        stop(tempo.cat)
    }
    # end required function checking
    # argument checking
    # argument checking with fun_check()
    arg.check <- NULL # for function debbuging
    checked.arg.names <- NULL # for function debbuging: used by r_debugging_tools
    ee <- expression(arg.check <- c(arg.check, tempo$problem) , checked.arg.names <- c(checked.arg.names, tempo$param.name))
    tempo <- fun_check(data = mat1, mode = "numeric", class = "matrix", na.contain = TRUE, neg.values = FALSE, fun.name = function.name) ; eval(ee)
    tempo <- fun_check(data = mat.hsv.h, class = "logical", length = 1, fun.name = function.name) ; eval(ee)
    tempo <- fun_check(data = notch, class = "vector", mode = "numeric", length = 1, prop = TRUE, fun.name = function.name) ; eval(ee)
    tempo <- fun_check(data = s, class = "vector", mode = "numeric", length = 1, prop = TRUE, fun.name = function.name) ; eval(ee)
    tempo <- fun_check(data = v, class = "vector", mode = "numeric", length = 1, prop = TRUE, fun.name = function.name) ; eval(ee)
    if(any(arg.check) == TRUE){
        stop() # nothing else because print = TRUE by default in fun_check()
    }
    # end argument checking with fun_check()
    # argument checking without fun_check()
    if(mat.hsv.h == TRUE & fun_check(data = mat1, mode = "numeric", prop = TRUE, print = FALSE)$problem == TRUE){
        tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": mat1 ARGUMENT MUST BE A MATRIX OF PROPORTIONS SINCE THE mat.hsv.h ARGUMENT IS SET TO TRUE\n\n================\n\n")
        stop(tempo.cat)
    }
    if( ! is.null(forced.color)){
        tempo <- fun_check(data = forced.color, class = "character")
        if(tempo$problem == TRUE){
            stop()
        }
        if( ! all(forced.color %in% colors() | grepl(pattern = "^#", forced.color))){ # check that all strings of forced.color start by #
            tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": forced.color ARGUMENT MUST BE A HEXADECIMAL COLOR VECTOR STARTING BY # AND/OR COLOR NAMES GIVEN BY colors()\n\n================\n\n")
            stop(tempo.cat)
        }
    }
    # end argument checking without fun_check()
    # source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.2/r_debugging_tools-v1.2.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
    problem <- NULL
    text.problem <- NULL
    mat1.name <- deparse(substitute(mat1))
    # change the scale of the plotted matrix
    if(mat.hsv.h == TRUE){
        if(any(min(mat1, na.rm = TRUE) < 0 | max(mat1, na.rm = TRUE) > 1, na.rm = TRUE)){
            tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": mat1 MUST BE MADE OF VALUES BETWEEN 0 AND 1 BECAUSE mat.hsv.h ARGUMENT SET TO TRUE\n\n================\n\n")
            stop(tempo.cat)
        }
    }else{
        if(any(mat1 - floor(mat1) > 0, na.rm = TRUE) | any(mat1 == 0, na.rm = TRUE)){
            tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": mat1 MUST BE MADE OF INTEGER VALUES WITHOUT 0 BECAUSE mat.hsv.h ARGUMENT SET TO FALSE\n\n================\n\n")
            stop(tempo.cat)
        }else{
            mat1 <- mat1 / max(mat1, na.rm = TRUE)
        }
    }
    if(notch != 1){
        different.color <- unique(as.vector(mat1))
        different.color <- different.color[ ! is.na(different.color)]
        tempo.different.color <- different.color + c(0, cumsum(rep(notch, length(different.color) - 1)))
        tempo.different.color <- tempo.different.color - floor(tempo.different.color)
        if(any(duplicated(tempo.different.color) == TRUE)){
            tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": DUPLICATED VALUES AFTER USING notch (", paste(tempo.different.color[duplicated(tempo.different.color)], collapse = " "), "). TRY ANOTHER notch VALUE\n\n================\n\n")
            stop(tempo.cat)
        }else if(length(different.color) != length(tempo.different.color)){
            tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": LENGTH OF different.color (", paste(different.color, collapse = " "), ") DIFFERENT FROM LENGTH OF tempo.different.color (", paste(tempo.different.color, collapse = " "), ")\n\n================\n\n")
            stop(tempo.cat)
        }else{
            for(i in 1:length(different.color)){
                mat1[mat1 == different.color[i]] <- tempo.different.color[i]
            }
        }
    }
    if( ! is.null(forced.color)){
        hexa.values.to.change <- hsv(unique(sort(mat1))[1:length(forced.color)], s, v)
    }
    mat1[ ! is.na(mat1)] <- hsv(mat1[ ! is.na(mat1)], s, v)
    if( ! is.null(forced.color)){
        if(any(forced.color %in% mat1, na.rm = TRUE)){
            problem <- TRUE
            text.problem <- paste0("THE FOLLOWING COLORS WHERE INTRODUCED USING forced.color BUT WHERE ALREADY PRESENT IN THE COLORED MATRIX :", paste(forced.color[forced.color %in% mat1], collapse = " "))
        }else{
            problem <- FALSE
        }
        for(i in 1:length(hexa.values.to.change)){
            if( ! any(mat1 == hexa.values.to.change[i], na.rm = TRUE)){
                tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": THE ", hexa.values.to.change[i], " VALUE FROM hexa.values.to.change IS NOT REPRESENTED IN mat1 : ", paste(unique(as.vector(mat1)), collapse = " "), "\n\n================\n\n")
                stop(tempo.cat)
            }else{
                mat1[which(mat1 == hexa.values.to.change[i])] <- forced.color[i]
            }
        }
    }
    output <- list(mat1.name = mat1.name, colored.mat = mat1, problem = problem, text.problem = text.problem)
    return(output)
Gael  MILLOT's avatar
Gael MILLOT committed
1838
}
Gael  MILLOT's avatar
Gael MILLOT committed
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


######## fun_mat_op() #### assemble several matrices with operation


# Check OK: clear to go Apollo
fun_mat_op <- function(mat.list, kind.of.operation = "+"){
    # AIM
    # assemble several matrices of same dimensions by performing by case operation. For instance add the value of all the case 1 (row1 & column1) of the matrices and put it in the case 1 of a new matrix M, add the value of all the case 2 (row2 & column1) of the matrices and put it in the case 2 of a new matrix M, etc.
    
    # c: case
    # i: row number
    # j: column number
    # k: matrix number
    # z: number of matrices
    # REQUIRED FUNCTIONS FROM CUTE_LITTLE_R_FUNCTION
    # fun_check()
    # fun_2d_comp()
    # ARGUMENTS:
    # mat.list: list of matrices
    # kind.of.operation: either "+" (by case addition), "-" (by case subtraction) or "*" (by case multiplication)
    # RETURN
    # the assembled matrix, with row and/or column names only if all the matrices have identical row/column names
    # EXAMPLES
    # mat1 = matrix(c(1,1,1,2,1,5,9,8), ncol = 2) ; mat2 = matrix(c(1,1,1,2,1,5,9,NA), ncol = 2) ; fun_mat_op(mat.list = list(mat1, mat2), kind.of.operation = "+")
    # mat1 = matrix(c(1,1,1,2,1,5,9,8), ncol = 2, dimnames = list(LETTERS[1:4], letters[1:2])) ; mat2 = matrix(c(1,1,1,2,1,5,9,NA), ncol = 2, dimnames = list(LETTERS[1:4], letters[1:2])) ; fun_mat_op(mat.list = list(mat1, mat2), kind.of.operation = "*")
    # mat1 = matrix(c(1,1,1,2,1,5,9,8), ncol = 2, dimnames = list(LETTERS[1:4], c(NA, NA))) ; mat2 = matrix(c(1,1,1,2,1,5,9,NA), ncol = 2, dimnames = list(LETTERS[1:4], letters[1:2])) ; fun_mat_op(mat.list = list(mat1, mat2), kind.of.operation = "-")
    # mat1 = matrix(c(1,1,1,2,1,5,9,8), ncol = 2, dimnames = list(c("A1", "A2", "A3", "A4"), letters[1:2])) ; mat2 = matrix(c(1,1,1,2,1,5,9,NA), ncol = 2, dimnames = list(LETTERS[1:4], letters[1:2])) ; mat3 = matrix(c(1,1,1,2,1,5,9,NA), ncol = 2, dimnames = list(LETTERS[1:4], letters[1:2])) ; fun_mat_op(mat.list = list(mat1, mat2, mat3), kind.of.operation = "+")
    # DEBUGGING
    # mat1 = matrix(c(1,1,1,2,1,5,9,8), ncol = 2) ; mat2 = matrix(c(1,1,1,2,1,5,9,NA), ncol = 2) ; mat.list = list(mat1, mat2) ; kind.of.operation = "+" # for function debugging
    # mat1 = matrix(c(1,1,1,2,1,5,9,8), ncol = 2, dimnames = list(LETTERS[1:4], c(NA, NA))) ; mat2 = matrix(c(1,1,1,2,1,5,9,NA), ncol = 2, dimnames = list(LETTERS[1:4], letters[1:2])) ; mat.list = list(mat1, mat2) ; kind.of.operation = "*" # for function debugging
    # function name
    function.name <- paste0(as.list(match.call(expand.dots=FALSE))[[1]], "()")
    # end function name
    # required function checking
    if(length(find("fun_check", mode = "function")) == 0){
        tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": REQUIRED fun_check() FUNCTION IS MISSING IN THE R ENVIRONMENT\n\n================\n\n")
        stop(tempo.cat)
    }
    if(length(find("fun_check", mode = "function")) == 0){
        tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": REQUIRED fun_2d_comp() FUNCTION IS MISSING IN THE R ENVIRONMENT\n\n================\n\n")
        stop(tempo.cat)
    }
    # end required function checking
    # argument checking
    # argument checking with fun_check()
    arg.check <- NULL # for function debbuging
    checked.arg.names <- NULL # for function debbuging: used by r_debugging_tools
    ee <- expression(arg.check <- c(arg.check, tempo$problem) , checked.arg.names <- c(checked.arg.names, tempo$param.name))
    tempo <- fun_check(data = mat.list, class = "list", fun.name = function.name) ; eval(ee)
    tempo <- fun_check(data = kind.of.operation, options = c("+", "-", "*"), length = 1, fun.name = function.name) ; eval(ee)
    if(any(arg.check) == TRUE){
        stop() # nothing else because print = TRUE by default in fun_check()
    }
    # end argument checking with fun_check()
    # argument checking without fun_check()
    if(length(mat.list) < 2){
        tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": mat.list ARGUMENT MUST BE A LIST CONTAINING AT LEAST 2 MATRICES\n\n================\n\n")
        stop(tempo.cat)
    }
    for(i0 in 1:length(mat.list)){
        tempo <- fun_check(data = mat.list[[i0]], class = "matrix", mode = "numeric", na.contain = TRUE)
        if(tempo$problem == TRUE){
            tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": ELEMENT ", i0, " OF mat.list ARGUMENT MUST BE A NUMERIC MATRIX\n\n================\n\n")
            stop(tempo.cat)
        }
    }
    ident.row.names <- TRUE
    ident.col.names <- TRUE
    for(i0 in 2:length(mat.list)){
        tempo <- fun_2d_comp(data1 = mat.list[[1]], data2 = mat.list[[i0]])
        if(tempo$same.dim == FALSE){
            tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": MATRIX ", i0, " OF mat.list ARGUMENT MUST HAVE THE SAME DIMENSION (", paste(dim(mat.list[[i0]]), collapse = " "), ") THAN THE MATRIX 1 IN mat.list (", paste(dim(mat.list[[1]]), collapse = " "), ")\n\n================\n\n")
            stop(tempo.cat)
        }
        if( ! is.null(tempo$same.row.name)){
            if(tempo$same.row.name != TRUE){ # != TRUE to deal with NA
                ident.row.names <- FALSE
            }
        }
        if( ! is.null(tempo$same.col.name)){
            if(tempo$same.col.name != TRUE){ # != TRUE to deal with NA
                ident.col.names <- FALSE
            }
        }
    }
    # end argument checking without fun_check()
    # source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.2/r_debugging_tools-v1.2.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
    output <- mat.list[[1]]
    for(i0 in 2:length(mat.list)){
        output <- get(kind.of.operation)(output, mat.list[[i0]])
    }
    dimnames(output) <- NULL
    if(ident.row.names == TRUE){
        rownames(output) <- rownames(mat.list[[1]])
    }
    if(ident.col.names == TRUE){
        colnames(output) <- colnames(mat.list[[1]])
    }
    return(output)
Gael  MILLOT's avatar
Gael MILLOT committed
1941
1942
1943
1944
}


######## fun_mat_inv() #### return the inverse of a square matrix
Gael  MILLOT's avatar
Gael MILLOT committed
1945
1946
1947
1948


# Check OK: clear to go Apollo
fun_mat_inv <- function(mat){
Gael  MILLOT's avatar
Gael MILLOT committed
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
    # AIM
    # return the inverse of a square matrix when solve() cannot
    # REQUIRED FUNCTIONS FROM CUTE_LITTLE_R_FUNCTION
    # fun_check()
    # ARGUMENTS:
    # mat: a square numeric matrix without NULL, NA, Inf or single case (dimension 1, 1) of 0
    # RETURN
    # the inversed matrix
    # EXAMPLES
    # mat1 = matrix(c(1,1,1,2,1,5,9,8,9), ncol = 3) ; fun_mat_inv(mat = mat1) # use solve()
    # mat1 = matrix(c(0,0,0,0,0,0,0,0,0), ncol = 3) ; fun_mat_inv(mat = mat1) # use the trick
    # mat1 = matrix(c(1,1,1,2,Inf,5,9,8,9), ncol = 3) ; fun_mat_inv(mat = mat1)
    # mat1 = matrix(c(1,1,1,2,NA,5,9,8,9), ncol = 3) ; fun_mat_inv(mat = mat1)
    # mat1 = matrix(c(1,2), ncol = 1) ; fun_mat_inv(mat = mat1)
    # mat1 = matrix(0, ncol = 1) ; fun_mat_inv(mat = mat1)
    # mat1 = matrix(2, ncol = 1) ; fun_mat_inv(mat = mat1)
    # DEBUGGING
    # mat = matrix(c(1,1,1,2,1,5,9,8,9), ncol = 3) # for function debugging
    # function name
    function.name <- paste0(as.list(match.call(expand.dots=FALSE))[[1]], "()")
    # end function name
    # required function checking
    if(length(find("fun_check", mode = "function")) == 0){
        tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": REQUIRED fun_check() FUNCTION IS MISSING IN THE R ENVIRONMENT\n\n================\n\n")
        stop(tempo.cat)
    }
    # end required function checking
    # argument checking
    # argument checking with fun_check()
    arg.check <- NULL # for function debbuging
    checked.arg.names <- NULL # for function debbuging: used by r_debugging_tools
    ee <- expression(arg.check <- c(arg.check, tempo$problem) , checked.arg.names <- c(checked.arg.names, tempo$param.name))
    tempo <- fun_check(data = mat, class = "matrix", mode = "numeric", fun.name = function.name) ; eval(ee)
    if(any(arg.check) == TRUE){
        stop() # nothing else because print = TRUE by default in fun_check()
    }
    # end argument checking with fun_check()
    # argument checking without fun_check()
    if(ncol(mat) != nrow(mat)){
        tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": mat ARGUMENT MUST BE A SQUARE MATRIX\n\n================\n\n")
        stop(tempo.cat)
    }
    if(any(mat %in% c(Inf, -Inf, NA))){
        tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": mat ARGUMENT MUST BE A MATRIX WITHOUT Inf, -Inf OR NA\n\n================\n\n")
        stop(tempo.cat)
    }
    if(all(mat == 0) & ncol(mat) == 1){
        tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": mat ARGUMENT CANNOT BE A SQUARE MATRIX MADE OF A SINGLE CASE OF 0\n\n================\n\n")
        stop(tempo.cat)
    }
    # end argument checking without fun_check()
    # source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.2/r_debugging_tools-v1.2.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(grepl(x = try(solve(mat), silent = TRUE)[], pattern = "[Ee]rror"))){
        tempo <- svd(mat)
        val.critique <- which(tempo$d < 10^-8)
        Diag.mod <- diag(1 / tempo$d)
        for(i in val.critique){
            Diag.mod[i, i] <- 0
        }
        return(tempo$v %*% Diag.mod %*% t(tempo$u))
    }else{
        return(solve(mat))
    }
Gael  MILLOT's avatar
Gael MILLOT committed
2014
2015
2016
2017
2018
2019
2020
}


######## fun_mat_fill() #### fill the empty half part of a symmetric square matrix


# Check OK: clear to go Apollo
Gael  MILLOT's avatar
Gael MILLOT committed
2021
fun_mat_fill <- function(mat, empty.cell.string = 0, warn.print = FALSE){
Gael  MILLOT's avatar
Gael MILLOT committed
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
    # AIM
    # detect the empty half part of a symmetric square matrix (either topleft, topright, bottomleft or bottomright)
    # fill this empty half part using the other symmetric half part of the matrix
    # WARNINGS
    # a plot verification using fun_gg_heatmap() is recommanded
    # REQUIRED FUNCTIONS FROM CUTE_LITTLE_R_FUNCTION
    # fun_check()
    # ARGUMENTS:
    # mat: a numeric or character square matrix with the half part (according to the grand diagonal) filled with NA (any kind of matrix), "0" (character matrix) or 0 (numeric matrix) exclusively (not a mix of 0 and NA in the empty part)
    # empty.cell.string: a numeric, character or NA (no quotes) indicating what empty cells are filled with
    # warn.print: logical. Print warnings at the end of the execution? No print if no warning messages
    # RETURN
    # a list containing:
    # $mat: the filled matrix
    # $warnings: the warning messages. Use cat() for proper display. NULL if no warning
    # EXAMPLES
    # mat1 = matrix(c(1,NA,NA,NA, 0,2,NA,NA, NA,3,4,NA, 5,6,7,8), ncol = 4) ; mat1 ; fun_mat_fill(mat = mat1, empty.cell.string = NA, warn.print = TRUE) # bottomleft example
    # mat1 = matrix(c(1,1,1,2, 0,2,3,0, NA,3,0,0, 5,0,0,0), ncol = 4) ; mat1 ; fun_mat_fill(mat = mat1, empty.cell.string = NA, warn.print = TRUE) # error example
    # mat1 = matrix(c(1,1,1,2, 0,2,3,0, NA,3,0,0, 5,0,0,0), ncol = 4) ; mat1 ; fun_mat_fill(mat = mat1, empty.cell.string = 0, warn.print = TRUE) # bottomright example
    # mat1 = matrix(c(1,1,1,2, "a",2,3,NA, "a","a",0,0, "a","a","a",0), ncol = 4) ; mat1 ; fun_mat_fill(mat = mat1, empty.cell.string = "a", warn.print = TRUE) # topright example
    # mat1 = matrix(c(0,0,0,2, 0,0,3,0, 0,3,0,NA, 5,0,0,0), ncol = 4) ; mat1 ; fun_mat_fill(mat = mat1, empty.cell.string = 0, warn.print = TRUE) # topleft example
    # mat1 = matrix(c(0,0,0,2, 0,0,3,0, 0,3,0,0, 5,0,0,0), ncol = 4) ; mat1 ; fun_mat_fill(mat = mat1, empty.cell.string = 0, warn.print = TRUE) # error example
    # DEBUGGING
    # mat = matrix(c(1,NA,NA,NA, 0,2,NA,NA, NA,3,4,NA, 5,6,7,8), ncol = 4) ; empty.cell.string = NA ; warn.print = TRUE # for function debugging
    # mat = matrix(c(0,0,0,2, 0,0,3,0, 0,3,0,NA, 5,0,0,0), ncol = 4) ; empty.cell.string = 0 ; warn.print = TRUE # for function debugging # topleft example
    # function name
    function.name <- paste0(as.list(match.call(expand.dots=FALSE))[[1]], "()")
    # end function name
    # required function checking
    if(length(find("fun_check", mode = "function")) == 0){
        tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": REQUIRED fun_check() FUNCTION IS MISSING IN THE R ENVIRONMENT\n\n================\n\n")
        stop(tempo.cat)
    }
    # end required function checking
    # argument checking
    # argument checking with fun_check()
    arg.check <- NULL # for function debbuging
    checked.arg.names <- NULL # for function debbuging: used by r_debugging_tools
    ee <- expression(arg.check <- c(arg.check, tempo$problem) , checked.arg.names <- c(checked.arg.names, tempo$param.name))
    tempo <- fun_check(data = mat, class = "matrix", na.contain = TRUE, fun.name = function.name) ; eval(ee)
    tempo <- fun_check(data = empty.cell.string, class = "vector", na.contain = TRUE, fun.name = function.name) ; eval(ee)
    tempo <- fun_check(data = warn.print, class = "logical", length = 1, fun.name = function.name) ; eval(ee)
    if(any(arg.check) == TRUE){
        stop() # nothing else because print = TRUE by default in fun_check()
    }
    # end argument checking with fun_check()
    # argument checking without fun_check()
    if(ncol(mat) != nrow(mat)){
        tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": mat ARGUMENT MUST BE A SQUARE MATRIX\n\n================\n\n")
        stop(tempo.cat)
    }
    if( ! (mode(mat) %in% c("numeric", "character"))){
        tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": mat ARGUMENT MUST BE A NUMERIC OR CHARACTER MATRIX\n\n================\n\n")
        stop(tempo.cat)
    }
    if(nrow(mat) == 1 & ncol(mat) == 1){
        tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": mat ARGUMENT CANNOT BE A SQUARE MATRIX MADE OF A SINGLE CASE\n\n================\n\n")
        stop(tempo.cat)
    }
    if(ifelse(is.na(empty.cell.string), ! any(is.na(mat)), ! any(mat == empty.cell.string, na.rm = TRUE))){
        tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": mat ARGUMENT MATRIX MUST HAVE CELLS WITH THE EMPTY STRING SPECIFIED IN empty.cell.string ARGUMENT\n\n================\n\n")
        stop(tempo.cat)
    }
    # end argument checking without fun_check()
    # source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.2/r_debugging_tools-v1.2.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
    list.diag <- vector("list", length = nrow(mat) - 1)
    for(i0 in 1:(nrow(mat) - 1)){
        list.diag[[i0]] <- numeric(length = nrow(mat) - i0)
    }
    sector <- c("topleft", "topright", "bottomright", "bottomleft")
    diag.scan <-c( # same order as sector. Recover each diag from center to corner
        "mat[as.matrix(as.data.frame(list(1:(nrow(mat) - i1), (ncol(mat) -i1):1)))]", # topleft part
        "mat[as.matrix(as.data.frame(list(1:(nrow(mat) - i1), (1:ncol(mat))[-(1:i1)])))]", # topright part
        "mat[as.matrix(as.data.frame(list((1 + i1):nrow(mat), ncol(mat):(1 + i1))))]", # bottomright part
        "mat[as.matrix(as.data.frame(list((1 + i1):nrow(mat), 1:(ncol(mat) -i1))))]" # bottomleft part
    )
    # empty part detection
    tempo.list.diag <- list.diag
    empty.sector <- NULL
    full.sector <- NULL
    warning <- NULL
    for(i0 in 1:length(sector)){
        tempo.list.diag <- list.diag
        for(i1 in 1:(nrow(mat) - 1)){
            tempo.list.diag[[i1]] <- eval(parse(text = diag.scan[i0]))
            if(ifelse(is.na(empty.cell.string), ! all(is.na(tempo.list.diag[[i1]])), ! (all(tempo.list.diag[[i1]] == empty.cell.string, na.rm = TRUE) & ! (is.na(all(tempo.list.diag[[i1]] == empty.cell.string, na.rm = FALSE)))))){ # I had to add this ! (is.na(all(tempo.list.diag[[i1]] == empty.cell.string, na.rm = FALSE))) because all(tempo.list.diag[[i1]] == empty.cell.string, na.rm = FALSE) gives NA and not FALSE if one NA in tempo.list.diag[[i1]] -> not good for if()
                full.sector <- c(full.sector, sector[i0])
                break
            }
        }
        if(i1 == nrow(mat) - 1){
            if(all(unlist(lapply(tempo.list.diag, FUN = function(x){if(is.na(empty.cell.string)){is.na(x)}else{x == empty.cell.string}})), na.rm = TRUE)){
                empty.sector <- c(empty.sector, sector[i0])
                tempo.warning <- paste0("FROM FUNCTION ", function.name, ": EMPTY SECTOR DETECTED ON THE ", toupper(sector[i0]), " CORNER, FULL OF ", empty.cell.string)
                warning <- paste0(ifelse(is.null(warning), tempo.warning, paste0(warning, "\n\n", tempo.warning)))
            }else{
                tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": THE ", toupper(sector[i0]), " SECTOR, DETECTED AS EMPTY, IS NOT? DIFFERENT VALUES IN THIS SECTOR:\n", paste(names(table(unlist(tempo.list.diag), useNA = "ifany")), collapse = " "), "\n\n================\n\n")
                stop(tempo.cat)
            }
        }
    }
    # end empty part detection
    if(length(empty.sector) == 0){
        tempo.warning <- paste0("FROM FUNCTION ", function.name, ": ACCORDING TO empty.cell.string ARGUMENT (", empty.cell.string, "), mat ARGUMENT MATRIX HAS ZERO EMPTY HALF PART")
        warning <- paste0(ifelse(is.null(warning), tempo.warning, paste0(warning, "\n\n", tempo.warning)))
    }else{
        if(length(empty.sector) > 1){
            tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": ACCORDING TO empty.cell.string ARGUMENT (", empty.cell.string, "), mat ARGUMENT MATRIX HAS MORE THAN ONE EMPTY HALF PART (ACCORDING TO THE GRAND DIAGONAL): ", paste(empty.sector, collapse = " "), "\n\n================\n\n")
            stop(tempo.cat)
        }else if(any(full.sector %in% empty.sector, na.rm = TRUE)){
            tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": THE FUNCTION HAS DETECTED EMPTY AND NON EMPTY HALF PART IN THE SAME SECTOR: ", paste(full.sector[full.sector %in% empty.sector], collapse = " "), "\n\n================\n\n")
            stop(tempo.cat)
        }else if(length(empty.sector) + length(full.sector)!= 4){
            tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": THE FUNCTION HAS DETECTED MORE OR LESS SECTORS THAN 4:\nEMPTY SECTORS:", paste(empty.sector, collapse = " "), "\nFULL SECTORS:", paste(full.sector, collapse = " "), "\n\n================\n\n")
            stop(tempo.cat)
        }
        # matrix filling
        for(i1 in 1:(nrow(mat) - 1)){
            if(empty.sector == "topleft"){
                eval(parse(text = paste0(diag.scan[1], " <- ", diag.scan[3])))
            }else if(empty.sector == "topright"){
                eval(parse(text = paste0(diag.scan[2], " <- ", diag.scan[4])))
            }else if(empty.sector == "bottomright"){
                eval(parse(text = paste0(diag.scan[3], " <- ", diag.scan[1])))
            }else if(empty.sector == "bottomleft"){
                eval(parse(text = paste0(diag.scan[4], " <- ", diag.scan[2])))
            }
        }
        # end matrix filling
    }
    if(warn.print == TRUE & ! is.null(warning)){
        warning(warning)
    }
    return(list(mat = mat, warnings = warning))
Gael  MILLOT's avatar
Gael MILLOT committed
2158
2159
2160
}


Gael  MILLOT's avatar
Gael MILLOT committed
2161
######## fun_permut() #### progressively breaks a vector order
Gael  MILLOT's avatar
Gael MILLOT committed
2162
2163


Gael  MILLOT's avatar
Gael MILLOT committed
2164
fun_permut <- function(data1, data2 = NULL, n = NULL, seed = NULL, count.print = 10, text.print = "", cor.method = "spearman", cor.limit = 0.2, warn.print = FALSE, path.lib = NULL){
Gael  MILLOT's avatar
Gael MILLOT committed
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
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
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
    # AIM
    # reorder the elements of the data1 vector by flipping 2 randomly selected  consecutive positions either:
    # 1) n times (when n is precised) or
    # 2) until the correlation between data1 and data2 decreases down to the cor.limit (0.2 by default). See cor.limit below to deal with negative correlations
    # Example of consecutive position flipping: ABCD -> BACD -> BADC, etc.
    # WARNINGS
    # see # https://www.r-bloggers.com/strategies-to-speedup-r-code/ for code speedup
    # the random switch of non consecutive positions (ABCD -> DBCA for instance) does not work very well as the correaltion is quickly obtained but the initial vector structure is mainly kept (no much order). Ths code would be: pos <- ini.pos[1:2] ; pos <- sample.int(n = n , size = 2, replace = FALSE) ; tempo.pos[pos] <- tempo.pos[rev(pos)]
    # ARGUMENTS
    # data1: a vector of at least 2 elements. Must be numeric if data2 is specified
    # data2: a numeric vector of same length as data1
    # n: number of times "flipping 2 randomly selected consecutive positions". Ignored if data2 is specified
    # seed: integer number used by set.seed(). Write NULL if random result is required, an integer otherwise. BEWARE: if not NULL, fun_permut() will systematically return the same result when the other parameters keep the same settings
    # count.print: interger value. Print a working progress message every count.print 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
    # text.print: optional message to add to the working progress message every count.print loop
    # cor.method: correlation method. Either "pearson", "kendall" or "spearman". Ignored if data2 is not specified
    # cor.limit: a correlation limit (between 0 and 1). Ignored if data2 is not specified. Compute the correlation between data1 and data2, permute the data1 values, and stop the permutation process when the correlation between data1 and data2 decreases down below the cor limit value (0.2 by default). If cor(data1, data2) is negative, then -cor.limit is used and the process stops until the correlation between data1 and data2 increases up over cor.limit (-0.2 by default). BEWARE: write a positive cor.limit even if cor(data1, data2) is known to be negative. The function will automatically uses -cor.limit. If the initial correlation is already below cor.limit (positive correlation) or over -cor.limit (negative correlation), then the data1 value positions are completely randomized (correlation between data1 and data2 is expected to be 0)
    # warn.print: logical. Print warnings at the end of the execution? No print if no warning messages
    # path.lib: absolute path of the required packages, if not in the default folders
    # REQUIRED PACKAGES
    # lubridate
    # REQUIRED FUNCTIONS FROM CUTE_LITTLE_R_FUNCTION
    # fun_check()
    # fun_pack()
    # fun_round()
    # RETURN
    # a list containing:
    # $data: the modified vector
    # $warnings: potential warning messages (in case of negative correlation when data2 is specified). NULL if non warning message
    # $cor: a spearman correlation between the initial positions (1:length(data1) and the final positions if data2 is not specified and the final correlation between data1 and data2 otherwise, according to cor.method
    # $count: the number of loops used
    # EXAMPLES
    # example (1) showing that for loop, used in fun_permut(), is faster than while loop
    # ini.time <- as.numeric(Sys.time()) ; count <- 0 ; for(i0 in 1:1e9){count <- count + 1} ; tempo.time <- as.numeric(Sys.time()) ; tempo.lapse <- round(lubridate::seconds_to_period(tempo.time - ini.time)) ; tempo.lapse
    # example (2) showing that for loop, used in fun_permut(), is faster than while loop
    # ini.time <- as.numeric(Sys.time()) ; count <- 0 ; while(count < 1e9){count <- count + 1} ; tempo.time <- as.numeric(Sys.time()) ; tempo.lapse <- round(lubridate::seconds_to_period(tempo.time - ini.time)) ; tempo.lapse
    # fun_permut(data1 = LETTERS[1:5], data2 = NULL, n = 100, seed = 1, count.print = 10, text.print = "CPU NB 4")
    # fun_permut(data1 = 101:110, data2 = 21:30, seed = 1, count.print = 1e4, text.print = "", cor.method = "spearman", cor.limit = 0.2)
    # a way to use the cor.limit argument just considering data1
    # obs1 <- 101:110 ; fun_permut(data1 = obs1, data2 = obs1, seed = 1, count.print = 10, cor.method = "spearman", cor.limit = 0.2)
    # fun_permut(data1 = 1:1e3, data2 = 1e3:1, seed = 1, count.print = 1e6, text.print = "", cor.method = "spearman", cor.limit = 0.7)
    # fun_permut(data1 = 1:1e2, data2 = 1e2:1, seed = 1, count.print = 1e3, cor.limit = 0.5)
    # fun_permut(data1 = c(0,0,0,0,0), n = 5, data2 = NULL, seed = 1, count.print = 1e3, cor.limit = 0.5)
    # DEBUGGING
    # data1 = LETTERS[1:5] ; data2 = NULL ; n = 1e6 ; seed = NULL ; count.print = 1e3 ; text.print = "" ; cor.method = "spearman" ; cor.limit = 0.2 ; warn.print = TRUE ; path.lib = NULL
    # data1 = LETTERS[1:5] ; data2 = NULL ; n = 10 ; seed = 22 ; count.print = 10 ; text.print = "" ; cor.method = "spearman" ; cor.limit = 0.2 ; warn.print = TRUE ; path.lib = NULL
    # data1 = 101:110 ; data2 = 21:30 ; n = 10 ; seed = 22 ; count.print = 10 ; text.print = "" ; cor.method = "spearman" ; cor.limit = 0.2 ; warn.print = TRUE ; path.lib = NULL
    # data1 = 1:1e3 ; data2 = 1e3:1 ; n = 20 ; seed = 22 ; count.print = 1e6 ; text.print = "" ; cor.method = "spearman" ; cor.limit = 0.5 ; warn.print = TRUE ; path.lib = NULL
    # function name
    function.name <- paste0(as.list(match.call(expand.dots=FALSE))[[1]], "()")
    # end function name
    # required function checking
    if(length(find("fun_check", mode = "function")) == 0){
        tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": REQUIRED fun_check() FUNCTION IS MISSING IN THE R ENVIRONMENT\n\n================\n\n")
        stop(tempo.cat)
    }
    if(length(find("fun_pack", mode = "function")) == 0){
        tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": REQUIRED fun_pack() FUNCTION IS MISSING IN THE R ENVIRONMENT\n\n================\n\n")
        stop(tempo.cat)
    }
    if(length(find("fun_round", mode = "function")) == 0){
        tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": REQUIRED fun_pack() FUNCTION IS MISSING IN THE R ENVIRONMENT\n\n================\n\n")
        stop(tempo.cat)
    }
    # end required function checking
    # argument checking
    arg.check <- NULL # for function debbuging
    checked.arg.names <- NULL # for function debbuging
    ee <- expression(arg.check <- c(arg.check, tempo$problem) , checked.arg.names <- c(checked.arg.names, tempo$param.name))
    tempo <- fun_check(data = data1, class = "vector", fun.name = function.name) ; eval(ee)
    if(tempo$problem == FALSE & length(data1) < 2){
        tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": data1 ARGUMENT MUST BE A VECTOR OF MINIMUM LENGTH 2. HERE IT IS: ", length(data1),"\n\n================\n\n")
        cat(tempo.cat)
        arg.check <- c(arg.check, TRUE)
    }
    if( ! is.null(data2)){
        tempo <- fun_check(data = data1, class = "vector", mode = "numeric", fun.name = function.name) ; eval(ee)
        if(tempo$problem == TRUE){
            tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": data1 MUST BE A NUMERIC VECTOR IF data2 ARGUMENT IS SPECIFIED\n\n================\n\n")
            cat(tempo.cat)
            arg.check <- c(arg.check, TRUE)
        }
        tempo <- fun_check(data = data2, class = "vector", mode = "numeric", fun.name = function.name) ; eval(ee)
        if(length(data1) != length(data2)){
            tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": data1 AND data2 MUST BE VECTOR OF SAME LENGTH. HERE IT IS ", length(data1)," AND ", length(data2), "\n\n================\n\n")
            cat(tempo.cat)
            arg.check <- c(arg.check, TRUE)
        }
    }else if(is.null(n)){
        tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": n ARGUMENT CANNOT BE NULL IF data2 ARGUMENT IS NULL\n\n================\n\n")
        cat(tempo.cat)
        arg.check <- c(arg.check, TRUE)
    }
    if( ! is.null(n)){
        tempo <- fun_check(data = n, class = "vector", typeof = "integer", length = 1, double.as.integer.allowed = TRUE, neg.values = FALSE, fun.name = function.name) ; eval(ee)
    }
    if( ! is.null(seed)){
        tempo <- fun_check(data = seed, class = "vector", typeof = "integer", length = 1, double.as.integer.allowed = TRUE, neg.values = FALSE, fun.name = function.name) ; eval(ee)
    }
    tempo <- fun_check(data = count.print, class = "vector", typeof = "integer", length = 1, double.as.integer.allowed = TRUE, neg.values = FALSE, fun.name = function.name) ; eval(ee)
    tempo <- fun_check(data = text.print, class = "character", length = 1, fun.name = function.name) ; eval(ee)
    tempo <- fun_check(data = cor.method, options = c("pearson", "kendall", "spearman"), length =1, fun.name = function.name) ; eval(ee)
    tempo <- fun_check(data = cor.limit, class = "vector", mode = "numeric", prop = TRUE, length = 1, fun.name = function.name) ; eval(ee)
    tempo <- fun_check(data = warn.print, class = "logical", length = 1, fun.name = function.name) ; eval(ee)
    if( ! is.null(path.lib)){
        tempo <- fun_check(data = path.lib, class = "character", fun.name = function.name) ; eval(ee)
        if(tempo$problem == FALSE & ! all(dir.exists(path.lib))){
            tempo.cat <- paste0("\n\n============\n\nERROR IN ", function.name, ": \nDIRECTORY PATH INDICATED IN THE path.lib PARAMETER DOES NOT EXISTS: ", path.lib, "\n\n============\n\n")
            cat(tempo.cat)
            arg.check <- c(arg.check, TRUE)
        }
    }
    if(any(arg.check) == TRUE){
        stop() # nothing else because print = TRUE by default in fun_check()
    }
    # source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.2/r_debugging_tools-v1.2.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
    # package checking
    fun_pack(req.package = "lubridate", path.lib = path.lib)
    # end package checking
    # main code
    # code that protects set.seed() in the global environment
    # see also Protocol 100-rev0 Parallelization in R.docx
    if(exists(".Random.seed", envir = .GlobalEnv)){ # if .Random.seed does not exists, it means that no random operation has been performed yet in any R environment
        tempo.random.seed <- .Random.seed
        on.exit(assign(".Random.seed", tempo.random.seed, env = .GlobalEnv))
    }else{
        on.exit(set.seed(NULL)) # inactivate seeding -> return to complete randomness
    }
    # end code that protects set.seed() in the global environment
    if( ! is.null(seed)){
        set.seed(seed)
    }
    ini.date <- Sys.time() # time of process begin, converted into seconds
    ini.time <- as.numeric(ini.date) # time of process begin, converted into seconds
    ini.pos <- 1:length(data1) # positions of data1 before permutation loops
    tempo.pos <- ini.pos # positions of data1 that will be modified during loops
    # pos.selec.seq <- ini.pos[-length(data1)] # selection of 1 position in initial position, without the last because always up permutation (pos -> pos+1 & pos+1 -> pos)
    pos.selec.seq.max <- length(ini.pos) - 1 # max position (used by sample.int() function). See  below for - 1
    warnings <- NULL
    count <- 0
    round <- 0
    BREAK <- FALSE
    tempo.cor <- 0
    if(is.null(data2)){
        if(length(table(data1)) == 1){
            tempo.warnings <- paste0("NO PERMUTATION PERFORMED BECAUSE data1 ARGUMENT SEEMS TO BE MADE OF IDENTICAL ELEMENTS: ", names(table(data1)))
            warnings <- paste0(warnings, ifelse(is.null(warnings), "", "\n"), tempo.warnings) #
        }else{
            if(count.print > n){
                count.print <- n
            }
            cat(paste0("\n", ifelse(text.print == "", "", paste0(text.print, " | ")), "FOR LOOP OF ", n, " LOOPS INITIATED | LOOP COUNT: ", format(count, big.mark=",")))
            count.print.loop <- logical(length = count.print)
            count.print.loop[length(count.print.loop)] <- TRUE # not this to avoid long vector, but not forget to reset during printing: count.print.loop[(1:trunc(n / count.print) * count.print)] <- TRUE # counter to speedup
            count.loop <- 0
            pos <- sample.int(n = pos.selec.seq.max , size = count.print, replace = TRUE) # selection of random positions. BEWARE: n = pos.selec.seq.max because already - 1 (see above) but is connected to tempo.pos[c(pos2 + 1, pos2)] <- tempo.pos[c(pos2, pos2 + 1)]
            tempo.date.loop <- Sys.time()
            tempo.time.loop <- as.numeric(tempo.date.loop)
            for(i3 in 1:n){
                count.loop <- count.loop + 1
                pos2 <- pos[count.loop] # selection of 1 position
                tempo.pos[c(pos2 + 1, pos2)] <- tempo.pos[c(pos2, pos2 + 1)]
                if(count.print.loop[count.loop]){
                    count.loop <- 0
                    pos <- sample.int(n = pos.selec.seq.max , size = count.print, replace = TRUE) # BEWARE: never forget to resample here
                    tempo.time <- as.numeric(Sys.time())
                    tempo.lapse <- round(lubridate::seconds_to_period(tempo.time - tempo.time.loop))
                    final.loop <- (tempo.time - tempo.time.loop) / i3 * n
                    final.exp <- as.POSIXct(final.loop, origin = tempo.date.loop)
                    cat(paste0("\n", ifelse(text.print == "", "", paste0(text.print, " | ")), "FOR LOOP ", i3, " / ", n, " | TIME SPENT: ", tempo.lapse, " | EXPECTED END: ", final.exp))
                }
            }
            count <- count + n # out of the loop to speedup
            cat(paste0("\n", ifelse(text.print == "", "", paste0(text.print, " | ")), "FOR LOOP ENDED | LOOP COUNT: ", format(count, big.mark=",")))
            cat("\n\n")
        }
    }else{
        if(length(table(data1)) == 1){
            tempo.warnings <- paste0("NO PERMUTATION PERFORMED BECAUSE data1 ARGUMENT SEEMS TO BE MADE OF IDENTICAL ELEMENTS: ", names(table(data1)))
            warnings <- paste0(warnings, ifelse(is.null(warnings), "", "\n"), tempo.warnings) #
            tempo.cor <- 1
        }else if(length(table(data2)) == 1){
            tempo.warnings <- paste0("NO PERMUTATION PERFORMED BECAUSE data2 ARGUMENT SEEMS TO BE MADE OF IDENTICAL ELEMENTS: ", names(table(data2)))
            warnings <- paste0(warnings, ifelse(is.null(warnings), "", "\n"), tempo.warnings) #
            tempo.cor <- 1
        }else{
            cor.ini <- cor(x = data1, y = data2, use = "pairwise.complete.obs", method = cor.method)
            tempo.cor <- cor.ini # correlation that will be modified during loops
            neg.cor <- FALSE
            if(tempo.cor < 0){
                tempo.warnings <- paste0("INITIAL ", toupper(cor.method), " CORRELATION BETWEEN data1 AND data2 HAS BEEN DETECTED AS NEGATIVE: ", tempo.cor, ". THE LOOP STEPS WILL BE PERFORMED USING POSITIVE CORRELATIONS BUT THE FINAL CORRELATION WILL BE NEGATIVE")
                warnings <- paste0(warnings, ifelse(is.null(warnings), "", "\n"), tempo.warnings) #
                neg.cor <- TRUE
                tempo.cor <- abs(tempo.cor)
                cor.ini <- abs(cor.ini)
            }
            if(tempo.cor < cor.limit){ # randomize directly all the position to be close to correlation zero
                tempo.warnings <- paste0("INITIAL ABSOLUTE VALUE OF THE ", toupper(cor.method), " CORRELATION ", fun_round(tempo.cor), " BETWEEN data1 AND data2 HAS BEEN DETECTED AS BELOW THE CORRELATION LIMIT PARAMETER ", cor.limit, "\nTHE data1 SEQUENCE HAS BEEN COMPLETELY RANDOMIZED TO CORRESPOND TO CORRELATION ZERO")
                warnings <- paste0(warnings, ifelse(is.null(warnings), "", "\n"), tempo.warnings) #
                for(i4 in 1:5){ # done 5 times to be sure of the complete randomness
                    tempo.pos <- sample(x = tempo.pos, size = length(tempo.pos), replace = FALSE)
                }
                count <- count + 5 # out of the loop to speedup
            }else{
                # smallest correlation decrease
                count <- count + 1 # 1 and not 0 because already 1 performed just below
                pos <- sample.int(n = pos.selec.seq.max , size = 1, replace = TRUE) # selection of 1 position # pos.selec.seq.max  because selection of 1 position in initial position, without the last because always up permutation (pos -> pos+1 & pos+1 -> pos)
                tempo.pos[c(pos + 1, pos)] <- tempo.pos[c(pos, pos + 1)]
                tempo.cor <- abs(cor(x = data1[tempo.pos], y = data2, use = "pairwise.complete.obs", method = cor.method))
                smallest.cor.dec <- cor.ini - tempo.cor
                # end smallest correlation decrease
                # going out of tempo.cor == cor.ini
                cat(paste0("\n", ifelse(text.print == "", "", paste0(text.print, " | ")), "CORRELATION DECREASE AFTER A SINGLE PERMUTATION: ", fun_round(smallest.cor.dec, 4)))
                cat(paste0("\n", ifelse(text.print == "", "", paste0(text.print, " | ")), "FIRST WHILE LOOP STEP -> GOING OUT FROM EQUALITY | LOOP COUNT: ", format(count, big.mark=","), " | CORRELATION LIMIT: ", fun_round(cor.limit, 4), " | ABS TEMPO CORRELATION: ", fun_round(tempo.cor, 4)))
                count.print.loop <- logical(length = count.print)
                count.print.loop[length(count.print.loop)] <- TRUE # counter to speedup
                count.loop <- 0 # 
                pos <- sample.int(n = pos.selec.seq.max , size = count.print, replace = TRUE) # selection of random positions. BEWARE: n = pos.selec.seq.max because already - 1 (see above) but is connected to tempo.pos[c(pos2 + 1, pos2)] <- tempo.pos[c(pos2, pos2 + 1)]
                tempo.date.loop <- Sys.time()
                tempo.time.loop <- as.numeric(tempo.date.loop)
                while(tempo.cor == cor.ini){ # to be out of equality between tempo.cor and cor.ini at the beginning (only valid for very long vector)
                    count <- count + 1
                    count.loop <- count.loop + 1
                    pos2 <- pos[count.loop]
                    tempo.pos[c(pos2 + 1, pos2)] <- tempo.pos[c(pos2, pos2 + 1)]
                    tempo.cor <- abs(cor(x = data1[tempo.pos], y = data2, use = "pairwise.complete.obs", method = cor.method))
                    if(count.print.loop[count.loop]){
                        count.loop <- 0
                        pos <- sample.int(n = pos.selec.seq.max , size = count.print, replace = TRUE) # BEWARE: never forget to resample here
                        tempo.time <- as.numeric(Sys.time())
                        tempo.lapse <- round(lubridate::seconds_to_period(tempo.time - tempo.time.loop))
                        cat(paste0("\n", ifelse(text.print == "", "", paste0(text.print, " | ")), "FIRST WHILE LOOP STEP", format(count.loop, big.mark=","), " / ? | COUNT: ", format(count, big.mark=","), " | CORRELATION LIMIT: ", fun_round(cor.limit, 4), " | ABS TEMPO CORRELATION: ", fun_round(tempo.cor, 4), " | TIME SPENT: ", tempo.lapse))
                    }
                }
                tempo.time <- as.numeric(Sys.time())
                tempo.lapse <- round(lubridate::seconds_to_period(tempo.time - ini.time))
                cat(paste0("\n", ifelse(text.print == "", "", paste0(text.print, " | ")), "FIRST WHILE LOOP STEP END | LOOP COUNT: ", format(count, big.mark=","), " | CORRELATION LIMIT: ", fun_round(cor.limit, 4), " | ABS TEMPO CORRELATION: ", fun_round(tempo.cor, 4), " | TOTAL SPENT TIME: ", tempo.lapse))
                if(tempo.cor < cor.limit){
                    tempo.warnings <- paste0("THE FIRST FOR & WHILE LOOP STEPS HAVE BEEN TOO FAR AND SUBSEQUENT LOOP STEPS WILL NOT RUN")
                    warnings <- paste0(warnings, ifelse(is.null(warnings), "", "\n"), tempo.warnings)
                }
                # end going out of tempo.cor == cor.ini
                # estimation of the average correlation decrease per loop on x loops and for loop execution
                cat(paste0("\n", ifelse(text.print == "", "", paste0(text.print, " | ")), "WHILE/FOR LOOPS INITIATION | LOOP COUNT: ", format(count, big.mark=","), " | CORRELATION LIMIT: ", fun_round(cor.limit, 4), " | ABS TEMPO CORRELATION: ", fun_round(tempo.cor, 4)))
                count.est <- 1e5
                first.round <- TRUE
                GOBACK <- FALSE
                while(tempo.cor > cor.limit){
                    round <- round + 1
                    # estimation step
                    if(first.round == TRUE){
                        first.round <- FALSE
                        cor.dec.per.loop <- numeric(length = 5)
                        loop.nb.est <- Inf
                        cor.est.ini <- tempo.cor
                        cor.est <- numeric(length = 5)
                        for(i6 in 1:5){ # connected to cor.dec.per.loop
                            tempo.pos.est <- tempo.pos
                            pos <- sample.int(n = pos.selec.seq.max , size = count.est, replace = TRUE) # selection of n position
                            for(i7 in 1:count.est){
                                pos2 <- pos[i7] # selection of 1 position
                                tempo.pos.est[c(pos2 + 1, pos2)] <- tempo.pos.est[c(pos2, pos2 + 1)]
                            }
                            tempo.cor.est <- abs(cor(x = data1[tempo.pos.est], y = data2, use = "pairwise.complete.obs", method = cor.method))
                            cor.est[i6] <- tempo.cor.est
                            tempo.cor.dec.per.loop <- (cor.est.ini - tempo.cor.est) / count.est # correlation decrease per loop
                            if(is.na(tempo.cor.dec.per.loop) | ! is.finite(tempo.cor.dec.per.loop)){
                                tempo.cat <- (paste0("\n\n============\n\nERROR IN ", function.name, ": CODE INCONSISTENCY 2\ncor.est.ini: ", cor.est.ini, "\ntempo.cor.est: ", tempo.cor.est, "\n\n============\n\n"))
                                stop(tempo.cat)
                            }
                            cor.dec.per.loop[i6] <- tempo.cor.dec.per.loop
                        }
                        cor.est <- cor.est[which.max(cor.dec.per.loop)] # max to avoid to go to far with for loop (tempo.cor below tempo.limit)
                        cor.dec.per.loop <- max(cor.dec.per.loop, na.rm = TRUE) # max to avoid to go to far with for loop (tempo.cor below tempo.limit)
                        loop.nb.est <- round((tempo.cor - cor.limit) / cor.dec.per.loop)
                    }else{
                        if(GOBACK == TRUE){
                            loop.nb.est <- round(loop.nb.est / 2)
                        }else{
                            cor.dec.per.loop <- (cor.ini - tempo.cor) / count
                            loop.nb.est <- round((tempo.cor - cor.limit) / cor.dec.per.loop)
                        }
                    }
                    # end estimation step
                    # loop step
                    if(is.na(loop.nb.est) | ! is.finite(loop.nb.est)){
                        tempo.cat <- (paste0("\n\n============\n\nERROR IN ", function.name, ": CODE INCONSISTENCY 1\nloop.nb.est: ", loop.nb.est, "\ncor.ini: ", cor.ini, "\ntempo.cor: ", tempo.cor, "\ncor.limit: ", cor.limit, "\ncor.dec.per.loop: ", cor.dec.per.loop, "\n\n============\n\n"))
                        stop(tempo.cat)
                    }else if(loop.nb.est > 1e4){ # below -> leave the while loop
                        tempo.pos.secu <- tempo.pos
                        count.secu <- count
                        tempo.cor.secu <- tempo.cor
                        cat(paste0("\n", ifelse(text.print == "", "", paste0(text.print, " | ")), "INITIAL SETTINGS BEFORE ROUND: ", round, " | LOOP COUNT: ", format(count, big.mark=","), " | GO BACK: ", GOBACK, " | LOOP NUMBER ESTIMATION: ", format(loop.nb.est, big.mark=","), " | CORRELATION LIMIT: ", fun_round(cor.limit, 4), " | ABS TEMPO CORRELATION: ", fun_round(tempo.cor, 4)))
                        count.print.loop <- logical(length = count.print)
                        count.print.loop[length(count.print.loop)] <- TRUE # not this to avoid long vector, but not forget to reset during printing: count.print.loop[(1:trunc(n / count.print) * count.print)] <- TRUE # counter to speedup
                        count.loop <- 0
                        pos <- sample.int(n = pos.selec.seq.max , size = count.print, replace = TRUE) # selection of random positions. BEWARE: n = pos.selec.seq.max because already - 1 (see above) but is connected to tempo.pos[c(pos2 + 1, pos2)] <- tempo.pos[c(pos2, pos2 + 1)]
                        tempo.date.loop <- Sys.time()
                        tempo.time.loop <- as.numeric(tempo.date.loop)
                        for(i6 in 1:loop.nb.est){
                            count.loop <- count.loop + 1
                            pos2 <- pos[count.loop] # selection of 1 position
                            tempo.pos[c(pos2 + 1, pos2)] <- tempo.pos[c(pos2, pos2 + 1)]
                            if(count.print.loop[count.loop]){
                                count.loop <- 0
                                pos <- sample.int(n = pos.selec.seq.max , size = count.print, replace = TRUE) # BEWARE: never forget to resample here
                                tempo.time <- as.numeric(Sys.time())
                                tempo.lapse <- round(lubridate::seconds_to_period(tempo.time - tempo.time.loop))
                                final.loop <- (tempo.time - tempo.time.loop) / i6 * loop.nb.est # intra nb.compar loop lapse: time lapse / cycles done * cycles remaining
                                final.exp <- as.POSIXct(final.loop, origin = tempo.date.loop)
                                cat(paste0("\n", ifelse(text.print == "", "", paste0(text.print, " | ")), "FOR LOOP | ROUND ", round, " | LOOP: ", format(i6, big.mark=","), " / ", format(loop.nb.est, big.mark=","), " | TIME SPENT: ", tempo.lapse, " | EXPECTED END: ", final.exp))
                            }
                        }
                        count <- count + loop.nb.est # out of the loop to speedup
                        tempo.cor <- abs(cor(x = data1[tempo.pos], y = data2, use = "pairwise.complete.obs", method = cor.method))
                        if(tempo.cor > tempo.cor.secu | ((tempo.cor - cor.limit) < 0 & abs(tempo.cor - cor.limit) > smallest.cor.dec * round(log10(max(ini.pos, na.rm = TRUE))))){
                            GOBACK <- TRUE
                            tempo.pos <- tempo.pos.secu
                            count <- count.secu
                            tempo.cor <- tempo.cor.secu
                        }else{
                            GOBACK <- FALSE
                        }
                    }else{
                        cat(paste0("\n", ifelse(text.print == "", "", paste0(text.print, " | ")), "FINAL WHILE LOOP | LOOP COUNT: ", format(count, big.mark=","), " | CORRELATION LIMIT: ", fun_round(cor.limit, 4), " | ABS TEMPO CORRELATION: ", fun_round(tempo.cor, 4)))
                        count.print.loop <- logical(length = count.print)
                        count.print.loop[length(count.print.loop)] <- TRUE # counter to speedup
                        count.loop <- 0 # 
                        pos <- sample.int(n = pos.selec.seq.max , size = count.print, replace = TRUE) # selection of random positions. BEWARE: n = pos.selec.seq.max because already - 1 (see above) but is connected to tempo.pos[c(pos2 + 1, pos2)] <- tempo.pos[c(pos2, pos2 + 1)]
                        tempo.cor.loop <- tempo.cor
                        tempo.date.loop <- Sys.time()
                        tempo.time.loop <- as.numeric(tempo.date.loop)
                        while(tempo.cor > cor.limit){
                            count <- count + 1
                            count.loop <- count.loop + 1
                            pos2 <- pos[count.loop]
                            tempo.pos[c(pos2 + 1, pos2)] <- tempo.pos[c(pos2, pos2 + 1)]
                            tempo.cor <- abs(cor(x = data1[tempo.pos], y = data2, use = "pairwise.complete.obs", method = cor.method))
                            if(count.print.loop[count.loop]){
                                count.loop <- 0
                                pos <- sample.int(n = pos.selec.seq.max , size = count.print, replace = TRUE) # BEWARE: never forget to resample here
                                tempo.time <- as.numeric(Sys.time())
                                tempo.lapse <- round(lubridate::seconds_to_period(tempo.time - tempo.time.loop))
                                final.loop <- (tempo.time - tempo.time.loop) / (tempo.cor.loop - tempo.cor) * (tempo.cor - cor.limit) # tempo.cor.loop - tempo.cor always positive and tempo.cor decreases progressively starting from tempo.cor.loop
                                final.exp <- as.POSIXct(final.loop, origin = tempo.date.loop)
                                cat(paste0("\n", ifelse(text.print == "", "", paste0(text.print, " | ")), "WHILE LOOP | LOOP NB: ", format(count.loop, big.mark=","), " | COUNT: ", format(count, big.mark=","), " | CORRELATION LIMIT: ", fun_round(cor.limit, 4), " | ABS TEMPO CORRELATION: ", fun_round(tempo.cor, 4), " | TIME SPENT: ", tempo.lapse, " | EXPECTED END: ", final.exp))
                            }
                        }
                    }
                }
                tempo.time <- as.numeric(Sys.time())
                tempo.lapse <- round(lubridate::seconds_to_period(tempo.time - ini.time))
                cat(paste0("\n", ifelse(text.print == "", "", paste0(text.print, " | ")), "WHILE/FOR LOOPS END | LOOP COUNT: ", format(count, big.mark=","), " | NB OF ROUNDS: ", round, " | CORRELATION LIMIT: ", fun_round(cor.limit, 4), " | ABS TEMPO CORRELATION: ", fun_round(tempo.cor, 4), " | TOTAL SPENT TIME: ", tempo.lapse))
            }
            tempo.cor <- ifelse(neg.cor == TRUE, -tempo.cor, tempo.cor)
        }
    }
    cat("\n\n")
    if(warn.print == TRUE & ! is.null(warning)){
        warning(warning)
        cat("\n\n")
    }
    output <- list(data = data1[tempo.pos], warnings = warnings, cor = if(is.null(data2)){cor(ini.pos, tempo.pos, method = "spearman")}else{tempo.cor}, count = count)
    return(output)
Gael  MILLOT's avatar
Gael MILLOT committed
2530
2531
2532
2533
}


################ Graphics management
Gael  MILLOT's avatar
Gael MILLOT committed
2534
2535
2536


# this order can be used:
Gael  MILLOT's avatar
Gael MILLOT committed
2537
2538
# fun_width()
# fun_open()
Gael  MILLOT's avatar
Gael MILLOT committed
2539
# fun_prior_plot() # not for ggplot2
Gael  MILLOT's avatar
Gael MILLOT committed
2540
# plot() or any other plotting
Gael  MILLOT's avatar
Gael MILLOT committed
2541
# fun_post_plot() if fun_prior_plot() has been used # not for ggplot2
Gael  MILLOT's avatar
Gael MILLOT committed
2542
# fun_close()
Gael  MILLOT's avatar
Gael MILLOT committed
2543
2544


Gael  MILLOT's avatar
Gael MILLOT committed
2545
######## fun_width() #### window width depending on classes to plot
Gael  MILLOT's avatar
Gael MILLOT committed
2546
2547
2548


# Check OK: clear to go Apollo
Gael  MILLOT's avatar
Gael MILLOT committed
2549
fun_width <- function(class.nb, inches.per.class.nb = 1, ini.window.width = 7, inch.left.space, inch.right.space, boundarie.space = 0.5){
Gael  MILLOT's avatar
Gael MILLOT committed
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
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
    # AIM
    # rescale the width of a window to open depending on the number of classes to plot
    # can be used for height, considering that it is as if it was a width
    # this order can be used:
    # fun_width()
    # fun_open()
    # fun_prior_plot() # not for ggplot2
    # plot() or any other plotting
    # fun_post_plot() if fun_prior_plot() has been used # not for ggplot2
    # fun_close()
    # REQUIRED FUNCTIONS FROM CUTE_LITTLE_R_FUNCTION
    # fun_check()
    # ARGUMENTS
    # class.nb: number of class to plot
    # inches.per.class.nb: number of inches per unit of class.nb. 2 means 2 inches for each boxplot for instance
    # ini.window.width:initial window width in inches
    # inch.left.space: left horizontal margin of the figure region (in inches)
    # inch.right.space: right horizontal margin of the figure region (in inches)
    # boundarie.space: space between the right and left limits of the plotting region and the plot (0.5 means half a class width)
    # RETURN
    # the new window width in inches
    # EXAMPLES
    # fun_width(class.nb = 10, inches.per.class.nb = 0.2, ini.window.width = 7, inch.left.space = 1, inch.right.space = 1, boundarie.space = 0.5)
    # DEBUGGING
    # class.nb = 10 ; inches.per.class.nb = 0.2 ; ini.window.width = 7 ; inch.left.space = 1 ; inch.right.space = 1 ; boundarie.space = 0.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(find("fun_check", mode = "function")) == 0){
        tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": REQUIRED fun_check() FUNCTION IS MISSING IN THE R ENVIRONMENT\n\n================\n\n")
        stop(tempo.cat)
    }
    # end required function checking
    # argument checking
    arg.check <- NULL # for function debbuging
    checked.arg.names <- NULL # for function debbuging: used by r_debugging_tools
    ee <- expression(arg.check <- c(arg.check, tempo$problem) , checked.arg.names <- c(checked.arg.names, tempo$param.name))
    tempo <- fun_check(data = class.nb, class = "vector", typeof = "integer", length = 1, double.as.integer.allowed = TRUE, neg.values = FALSE, fun.name = function.name) ; eval(ee)
    tempo <- fun_check(data = inches.per.class.nb, class = "vector", mode = "numeric", length = 1, neg.values = FALSE, fun.name = function.name) ; eval(ee)
    tempo <- fun_check(data = ini.window.width, class = "vector", mode = "numeric", length = 1, neg.values = FALSE, fun.name = function.name) ; eval(ee)
    tempo <- fun_check(data = inch.left.space, class = "vector", mode = "numeric", length = 1, neg.values = FALSE, fun.name = function.name) ; eval(ee)
    tempo <- fun_check(data = inch.right.space, class = "vector", mode = "numeric", length = 1, neg.values = FALSE, fun.name = function.name) ; eval(ee)
    tempo <- fun_check(data = boundarie.space, class = "vector", mode = "numeric", length = 1, neg.values = FALSE, fun.name = function.name) ; eval(ee)
    if(any(arg.check) == TRUE){
        stop() # nothing else because print = TRUE by default in fun_check()
    }
    # source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.2/r_debugging_tools-v1.2.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
    range.max <- class.nb + boundarie.space # the max range of the future plot
    range.min <- boundarie.space # the min range of the future plot
    window.width <- inch.left.space + inch.right.space + inches.per.class.nb * (range.max - range.min)
    return(window.width)
Gael  MILLOT's avatar
Gael MILLOT committed
2604
2605
2606
}


Gael  MILLOT's avatar
Gael MILLOT committed
2607
######## fun_open() #### open a GUI or pdf graphic window
Gael  MILLOT's avatar
Gael MILLOT committed
2608
2609
2610


# Check OK: clear to go Apollo
Gael  MILLOT's avatar
Gael MILLOT committed
2611
fun_open <- function(pdf.disp = TRUE, path.fun = "working.dir", pdf.name.file = "graph", width.fun = 7, height.fun = 7, paper = "special", no.pdf.overwrite = TRUE, return.output = FALSE){
Gael  MILLOT's avatar
Gael MILLOT committed
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
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
    # AIM
    # open a pdf or screen (GUI) graphic window
    # BEWARE: on Linux, use pdf.disp = TRUE, if (GUI) graphic window is not always available, meaning that X is not installed (clusters for instance). Use X11() in R to test if available
    # this order can be used:
    # fun_width()
    # fun_open()
    # fun_prior_plot() # not for ggplot2
    # plot() or any other plotting
    # fun_post_plot() if fun_prior_plot() has been used # not for ggplot2
    # fun_close()
    # REQUIRED FUNCTIONS FROM CUTE_LITTLE_R_FUNCTION
    # fun_check()
    # ARGUMENTS:
    # pdf.disp: use pdf or not
    # path.fun: where the pdf is saved (do not terminate by / or \\). Write "working.dir" if working directory is required (default)
    # pdf.name.file: name of the pdf file containing the graphs (the .pdf extension is added by the function)
    # width.fun: width of the windows (in inches)
    # height.fun: height of the windows (in inches)
    # paper: paper argument of the pdf function (paper format). Only used for pdf(). Either "a4", "letter", "legal", "us", "executive", "a4r", "USr" or "special". If "special", means that width.fun and height.fun specify the paper size
    # no.pdf.overwrite: existing pdf can be overwritten ? Only used if pdf.disp = TRUE
    # return.output: return output ? If TRUE but function not assigned, the output list is displayed
    # RETURN
    # a list containing:
    # $pdf.loc: path of the pdf created
    # $ini.par: initial par() parameters (to reset in a new graph)
    # $zone.ini: initial window spliting (to reset in a new graph)
    # EXAMPLES
    # fun_open(pdf.disp = FALSE, path.fun = "C:/Users/Gael/Desktop", pdf.name.file = "graph", width.fun = 7, height.fun = 7, paper = "special", no.pdf.overwrite = TRUE, return.output = TRUE)
    # DEBUGGING
    # pdf.disp = TRUE ; path.fun = "C:/Users/Gael/Desktop" ; pdf.name.file = "graphs" ; width.fun = 7 ; height.fun = 7 ; paper = "special" ; no.pdf.overwrite = TRUE ; return.output = TRUE # for function debugging
    # pdf.disp = TRUE ; path.fun = "/pasteur/homes/gmillot/" ; pdf.name.file = "graphs" ; width.fun = 7 ; height.fun = 7 ; paper = "special" ; no.pdf.overwrite = TRUE ; return.output = TRUE # for function debugging
    # function name
    function.name <- paste0(as.list(match.call(expand.dots=FALSE))[[1]], "()")
    # end function name
    # required function checking
    if(length(find("fun_check", mode = "function")) == 0){
        tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": REQUIRED fun_check() FUNCTION IS MISSING IN THE R ENVIRONMENT\n\n================\n\n")
        stop(tempo.cat)
    }
    # end required function checking
    # argument checking
    arg.check <- NULL # for function debbuging
    checked.arg.names <- NULL # for function debbuging: used by r_debugging_tools
    ee <- expression(arg.check <- c(arg.check, tempo$problem) , checked.arg.names <- c(checked.arg.names, tempo$param.name))
    tempo <- fun_check(data = pdf.disp, class = "logical", length = 1, fun.name = function.name) ; eval(ee)
    tempo <- fun_check(data = path.fun, class = "character", length = 1, fun.name = function.name) ; eval(ee)
    tempo <- fun_check(data = pdf.name.file, class = "character", length = 1, fun.name = function.name) ; eval(ee)
    tempo <- fun_check(data = width.fun, class = "vector", mode = "numeric", length = 1, neg.values = FALSE, fun.name = function.name) ; eval(ee)
    tempo <- fun_check(data = height.fun, class = "vector", mode = "numeric", length = 1, neg.values = FALSE, fun.name = function.name) ; eval(ee)
    tempo <- fun_check(data = path.fun, class = "character", length = 1, fun.name = function.name) ; eval(ee)
    tempo <- fun_check(data = paper, options = c("a4", "letter", "legal", "us", "executive", "a4r", "USr", "special", "A4", "LETTER", "LEGAL", "US"), length = 1, fun.name = function.name) ; eval(ee)
    tempo <- fun_check(data =no.pdf.overwrite, class = "logical", length = 1, fun.name = function.name) ; eval(ee)
    tempo <- fun_check(data = return.output, class = "logical", length = 1, fun.name = function.name) ; eval(ee)
    if(any(arg.check) == TRUE){
        stop() # nothing else because print = TRUE by default in fun_check()
    }
    # source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.2/r_debugging_tools-v1.2.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(path.fun == "working.dir"){
        path.fun <- getwd()
    }else{
        if(grepl(x = path.fun, pattern = ".+/$")){
            path.fun <- substr(path.fun, 1, nchar(path.fun) - 1) # remove the last /
        }
        if(dir.exists(path.fun) == FALSE){
            tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": path.fun ARGUMENT DOES NOT CORRESPOND TO EXISTING DIRECTORY\n\n================\n\n")
            stop(tempo.cat)
        }
    }
    if(Sys.info()["sysname"] == "Windows"){ # Note that .Platform$OS.type() only says "unix" for macOS and Linux and "Windows" for Windows
        open.fail <- NULL
        windows()
        ini.par <- par(no.readonly = TRUE) # to recover the initial graphical parameters if required (reset). BEWARE: this command alone opens a pdf of GUI window if no window already opened. But here, protected with the code because always a tempo window opened
        invisible(dev.off()) # close the new window
    }else if(Sys.info()["sysname"] == "Linux"){
        if(pdf.disp == TRUE){
            if(file.exists(paste0(path.fun, "/recover_ini_par.pdf"))){
                tempo.cat <- paste0("\n\n================\n\nPROBLEM IN fun_open(): THIS FUNCTION CANNOT BE USED ON LINUX IF A recover_ini_par.pdf FILE ALREADY EXISTS HERE: ", paste(path.fun, collapse = " "), "\n\n================\n\n")
                stop(tempo.cat)
            }else{
                pdf(width = width.fun, height = height.fun, file=paste0(path.fun, "/recover_ini_par.pdf"), paper = paper)
                ini.par <- par(no.readonly = TRUE) # to recover the initial graphical parameters if required (reset). BEWARE: this command alone opens a pdf of GUI window if no window already opened. But here, protected with the code because always a tempo window opened
                invisible(dev.off()) # close the pdf windows
                file.remove(paste0(path.fun, "/recover_ini_par.pdf")) # remove the pdf file
            }
        }else{
            # test if X11 can be opened
            if(file.exists(paste0(getwd(), "/Rplots.pdf"))){
                tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": THIS FUNCTION CANNOT BE USED ON LINUX IF A Rplots.pdf FILE ALREADY EXISTS HERE: ", getwd(), "\n\n================\n\n")
                stop(tempo.cat)
            }else{
                open.fail <- suppressWarnings(try(X11(), silent = TRUE))[] # try to open a X11 window. If open.fail == NULL, no problem, meaning that the X11 window is opened. If open.fail != NULL, a pdf can be opened here paste0(getwd(), "/Rplots.pdf")
                if(is.null(open.fail)){
                    ini.par <- par(no.readonly = TRUE) # to recover the initial graphical parameters if required (reset). BEWARE: this command alone opens a pdf of GUI window if no window already opened. But here, protected with the code because always a tempo window opened
                    invisible(dev.off()) # close the new window
                }else if(file.exists(paste0(getwd(), "/Rplots.pdf"))){
                    file.remove(paste0(getwd(), "/Rplots.pdf")) # remove the pdf file
                    tempo.cat <- ("\n\n================\n\nPROBLEM IN fun_open(): THIS FUNCTION CANNOT OPEN GUI ON LINUX OR NON MACOS UNIX SYSTEM (X GRAPHIC INTERFACE HAS TO BE SET).\nTO OVERCOME THIS, PLEASE SET pdf.disp ARGUMENT TO TRUE AND RERUN\n\n================\n\n")
                    stop(tempo.cat)
                }
            }
        }
    }else{
        open.fail <- NULL
        quartz()
        ini.par <- par(no.readonly = TRUE) # to recover the initial graphical parameters if required (reset). BEWARE: this command alone opens a pdf of GUI window if no window already opened. But here, protected with the code because always a tempo window opened
        invisible(dev.off()) # close the new window
    }
    zone.ini <- matrix(1, ncol=1) # to recover the initial parameters for next figure region when device region split into several figure regions
    if(pdf.disp == TRUE){
        pdf.loc <- paste0(path.fun, "/", pdf.name.file, ".pdf")
        if(file.exists(pdf.loc) == TRUE & no.pdf.overwrite == TRUE){
            tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": pdf.loc FILE ALREADY EXISTS AND CANNOT BE OVERWRITTEN DUE TO no.pdf.overwrite ARGUMENT SET TO TRUE: ", pdf.loc, "\n\n================\n\n")
            stop(tempo.cat)
        }else{
            pdf(width = width.fun, height = height.fun, file=pdf.loc, paper = paper)
        }
    }else if(pdf.disp == FALSE){
        pdf.loc <- NULL
        if(Sys.info()["sysname"] == "Windows"){ # .Platform$OS.type() only says "unix" for macOS and Linux and "Windows" for Windows
            windows(width = width.fun, height = height.fun, rescale="fixed")
        }else if(Sys.info()["sysname"] == "Linux"){
            if( ! is.null(open.fail)){
                stop("\n\n================\n\nPROBLEM IN fun_open(): THIS FUNCTION CANNOT OPEN GUI ON LINUX OR NON MACOS UNIX SYSTEM (X GRAPHIC INTERFACE HAS TO BE SET).\nTO OVERCOME THIS, PLEASE SET pdf.disp ARGUMENT TO TRUE AND RERUN\n\n================\n\n")
            }else{
                X11(width = width.fun, height = height.fun)
            }
        }else{
            quartz(width = width.fun, height = height.fun)
        }
    }
    if(return.output == TRUE){
        output <- list(pdf.loc = pdf.loc, ini.par = ini.par, zone.ini = zone.ini)
        return(output)
    }
Gael  MILLOT's avatar
Gael MILLOT committed
2748
2749
2750
}


2751
######## fun_prior_plot() #### set graph param before plotting (erase axes for instance)
Gael  MILLOT's avatar
Gael MILLOT committed
2752
2753
2754


# Check OK: clear to go Apollo
Gael  MILLOT's avatar
Gael MILLOT committed
2755
fun_prior_plot <- function(param.reinitial = FALSE, xlog.scale = FALSE, ylog.scale = FALSE, remove.label = TRUE, remove.x.axis = TRUE, remove.y.axis = TRUE, std.x.range = TRUE, std.y.range = TRUE, down.space = 1, left.space = 1, up.space = 1, right.space = 1, orient = 1, dist.legend = 3.5, tick.length = 0.5, box.type = "n", amplif.label = 1, amplif.axis = 1, display.extend = FALSE, return.par = FALSE){
Gael  MILLOT's avatar
Gael MILLOT committed
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
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
    # AIM
    # very convenient to erase the axes for post plot axis redrawing using fun_post_plot()
    # reinitialize and set the graphic parameters before plotting
    # CANNOT be used if no graphic device already opened
    # REQUIRED FUNCTIONS FROM CUTE_LITTLE_R_FUNCTION
    # fun_check()
    # ARGUMENTS
    # param.reinitial: reinitialize graphic parameters before applying the new ones, as defined by the other arguments? Either TRUE or FALSE
    # xlog.scale: Log scale for the x-axis? Either TRUE or FALSE. If TRUE, erases the x-axis, except legend, for further drawing by fun_post_plot()(xlog argument of par())
    # ylog.scale: Log scale for the y-axis? Either TRUE or FALSE. If TRUE, erases the y-axis, except legend, for further drawing by fun_post_plot()(ylog argument of par())
    # remove.label: remove labels (axis legend) of the two axes? Either TRUE or FALSE (ann argument of par())
    # remove.x.axis: remove x-axis except legend? Either TRUE or FALSE (control the xaxt argument of par()). Automately set to TRUE if xlog.scale == TRUE
    # remove.y.axis: remove y-axis except legend? Either TRUE or FALSE (control the yaxt argument of par()). Automately set to TRUE if ylog.scale == TRUE
    # std.x.range: standard range on the x-axis? TRUE (no range extend) or FALSE (4% range extend). Controls xaxs argument of par() (TRUE is xaxs = "i", FALSE is xaxs = "r")
    # std.y.range: standard range on the y-axis? TRUE (no range extend) or FALSE (4% range extend). Controls yaxs argument of par() (TRUE is yaxs = "i", FALSE is yaxs = "r")
    # down.space: lower vertical margin (in inches, mai argument of par())
    # left.space: left horizontal margin (in inches, mai argument of par())
    # up.space: upper vertical margin between plot region and grapical window (in inches, mai argument of par())
    # right.space: right horizontal margin (in inches, mai argument of par())
    # orient: scale number orientation (las argument of par()). 0, always parallel to the axis; 1, always horizontal; 2, always perpendicular to the axis; 3, always vertical
    # dist.legend: numeric value that moves axis legends away in inches (first number of mgp argument of par() but in inches thus / 0.2)
    # tick.length: length of the ticks (1 means complete the distance between the plot region and the axis numbers, 0.5 means half the length, etc. 0 means no tick
    # box.type: bty argument of par(). Either "o", "l", "7", "c", "u", "]", the resulting box resembles the corresponding upper case letter. A value of "n" suppresses the box
    # amplif.label: increase or decrease the size of the text in legends
    # amplif.axis: increase or decrease the size of the scale numbers in axis
    # display.extend: extend display beyond plotting region? Either TRUE or FALSE (xpd argument of par() without NA)
    # return.par: return graphic parameter modification?
    # RETURN
    # return graphic parameter modification
    # EXAMPLES
    # fun_prior_plot(param.reinitial = FALSE, xlog.scale = FALSE, ylog.scale = FALSE, remove.label = TRUE, remove.x.axis = TRUE, remove.y.axis = TRUE, std.x.range = TRUE, std.y.range = TRUE, down.space = 1, left.space = 1, up.space = 1, right.space = 1, orient = 1, dist.legend = 4.5, tick.length = 0.5, box.type = "n", amplif.label = 1, amplif.axis = 1, display.extend = FALSE, return.par = FALSE)
    # DEBUGGING
    # param.reinitial = FALSE ; xlog.scale = FALSE ; ylog.scale = FALSE ; remove.label = TRUE ; remove.x.axis = TRUE ; remove.y.axis = TRUE ; std.x.range = TRUE ; std.y.range = TRUE ; down.space = 1 ; left.space = 1 ; up.space = 1 ; right.space = 1 ; orient = 1 ; dist.legend = 4.5 ; tick.length = 0.5 ; box.type = "n" ; amplif.label = 1 ; amplif.axis = 1 ; display.extend = FALSE ; return.par = FALSE # for function debugging
    # function name
    function.name <- paste0(as.list(match.call(expand.dots=FALSE))[[1]], "()")
    # end function name
    # required function checking
    if(length(find("fun_check", mode = "function")) == 0){
        tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": REQUIRED fun_check() FUNCTION IS MISSING IN THE R ENVIRONMENT\n\n================\n\n")
        stop(tempo.cat)
    }
    # end required function checking
    # argument checking
    arg.check <- NULL # for function debbuging
    checked.arg.names <- NULL # for function debbuging: used by r_debugging_tools
    ee <- expression(arg.check <- c(arg.check, tempo$problem) , checked.arg.names <- c(checked.arg.names, tempo$param.name))
    tempo <- fun_check(data = param.reinitial, class = "logical", length = 1, fun.name = function.name) ; eval(ee)
    tempo <- fun_check(data = xlog.scale, class = "logical", length = 1, fun.name = function.name) ; eval(ee)
    tempo <- fun_check(data = ylog.scale, class = "logical", length = 1, fun.name = function.name) ; eval(ee)
    tempo <- fun_check(data = remove.label, class = "logical", length = 1, fun.name = function.name) ; eval(ee)
    tempo <- fun_check(data = remove.x.axis, class = "logical", length = 1, fun.name = function.name) ; eval(ee)
    tempo <- fun_check(data = remove.y.axis, class = "logical", length = 1, fun.name = function.name) ; eval(ee)
    tempo <- fun_check(data = std.x.range, class = "logical", length = 1, fun.name = function.name) ; eval(ee)
    tempo <- fun_check(data = std.y.range, class = "logical", length = 1, fun.name = function.name) ; eval(ee)
    tempo <- fun_check(data = down.space, class = "vector", mode = "numeric", length = 1, neg.values = FALSE, fun.name = function.name) ; eval(ee)
    tempo <- fun_check(data = left.space, class = "vector", mode = "numeric", length = 1, neg.values = FALSE, fun.name = function.name) ; eval(ee)
    tempo <- fun_check(data = up.space, class = "vector", mode = "numeric", length = 1, neg.values = FALSE, fun.name = function.name) ; eval(ee)
    tempo <- fun_check(data = right.space, class = "vector", mode = "numeric", length = 1, neg.values = FALSE, fun.name = function.name) ; eval(ee)
    tempo <- fun_check(data = orient, class = "vector", mode = "numeric", length = 1, neg.values = FALSE, fun.name = function.name) ; eval(ee)
    tempo <- fun_check(data = dist.legend, class = "vector", mode = "numeric", length = 1, neg.values = FALSE, fun.name = function.name) ; eval(ee)
    tempo <- fun_check(data = tick.length, class = "vector", mode = "numeric", length = 1, prop = TRUE, fun.name = function.name) ; eval(ee)
    tempo <- fun_check(data = box.type, options = c("o", "l", "7", "c", "u", "]", "n"), length = 1, fun.name = function.name) ; eval(ee)
    tempo <- fun_check(data = amplif.label, class = "vector", mode = "numeric", length = 1, neg.values = FALSE, fun.name = function.name) ; eval(ee)
    tempo <- fun_check(data = amplif.axis, class = "vector", mode = "numeric", length = 1, neg.values = FALSE, fun.name = function.name) ; eval(ee)
    tempo <- fun_check(data = display.extend, class = "logical", length = 1, fun.name = function.name) ; eval(ee)
    tempo <- fun_check(data = return.par, class = "logical", length = 1, fun.name = function.name) ; eval(ee)
    if(any(arg.check) == TRUE){
        stop() # nothing else because print = TRUE by default in fun_check()
    }
    # source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.2/r_debugging_tools-v1.2.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(is.null(dev.list())){
        tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": THIS FUNCTION CANNOT BE USED IF NO GRAPHIC DEVICE ALREADY OPENED (dev.list() IS CURRENTLY NULL)\n\n================\n\n")
        stop(tempo.cat)
    }
    if(param.reinitial == TRUE){
        if( ! all(names(dev.cur()) == "null device")){
            active.wind.nb <- dev.cur()
        }else{
            active.wind.nb <- 0
        }
        if(Sys.info()["sysname"] == "Windows"){ # Note that .Platform$OS.type() only says "unix" for macOS and Linux and "Windows" for Windows
            windows()
            ini.par <- par(no.readonly = TRUE) # to recover the initial graphical parameters if required (reset). BEWARE: this command alone opens a pdf of GUI window if no window already opened. But here, protected with the code because always a tempo window opened
            invisible(dev.off()) # close the new window
        }else if(Sys.info()["sysname"] == "Linux"){
            if(file.exists(paste0(getwd(), "/Rplots.pdf"))){
                tempo.cat <- paste0("\n\n================\n\nERROR IN ", function.name, ": THIS FUNCTION CANNOT BE USED ON LINUX WITH param.reinitial SET TO TRUE IF A Rplots.pdf FILE ALREADY EXISTS HERE: ", getwd(), "\n\n================\n\n")
                stop(tempo.cat)
            }else{
                open.fail <- suppressWarnings(try(X11(), silent = TRUE))[] # try to open a X11 window. If open.fail == NULL, no problem, meaning that the X11 window is opened. If open.fail != NULL, a pdf can be opened here paste0(getwd(), "/Rplots.pdf")
                if(is.null(open.fail)){
                    ini.par <- par(no.readonly = TRUE) # to recover the initial graphical parameters if required (reset). BEWARE: this command alone opens a pdf of GUI window if no window already opened. But here, protected with the code because always a tempo window opened
                    invisible(dev.off()) # close the new window
                }else if(file.exists(paste0(getwd(), "/Rplots.pdf"))){
                    ini.par <- par(no.readonly = TRUE) # to recover the initial graphical parameters if required (reset). BEWARE: this command alone opens a pdf of GUI window if no window already opened. But here, protected with the code because always a tempo window opened
                    invisible(dev.off()) # close the new window
                    file.remove(paste0(getwd(), "/Rplots.pdf")) # remove the pdf file
                }else{
                    tempo.cat <- ("\n\n================\n\nPROBLEM IN fun_prior_plot(): THIS FUNCTION CANNOT OPEN GUI ON LINUX OR NON MACOS UNIX SYSTEM (X GRAPHIC INTERFACE HAS TO BE SET).\nTO OVERCOME THIS, PLEASE USE PDF GRAPHIC INTERFACES AND RERUN\n\n================\n\n")
                    stop(tempo.cat)
                }
            }
        }else{ # macOS
            quartz()
            ini.par <- par(no.readonly = TRUE) # to recover the initial graphical parameters if required (reset). BEWARE: this command alone opens a pdf of GUI window if no window already opened. But here, protected with the code because always a tempo window opened)
            invisible(dev.off()) # close the new window
        }
        if( ! all(names(dev.cur()) == "null device")){
            dev.set(active.wind.nb) # go back to the active windows if exists
            par(ini.par) # apply the initial par to current window
        }
    }
    if(remove.x.axis == TRUE){
        par(xaxt = "n") # suppress the y-axis label
    }else{
        par(xaxt = "s")
    }
    if(remove.y.axis == TRUE){
        par(yaxt = "n") # suppress the y-axis label
    }else{
        par(yaxt = "s")
    }
    if(std.x.range == TRUE){
        par(xaxs = "i")
    }else{
        par(xaxs = "r")
    }
    if(std.y.range == TRUE){
        par(yaxs = "i")
    }else{
        par(yaxs = "r")
    }
    par(mai = c(down.space, left.space, up.space, right.space), ann = ! remove.label, las = orient, mgp = c(dist.legend/0.2, 1, 0), xpd = display.extend, bty= box.type, cex.lab = amplif.label, cex.axis = amplif.axis)
    par(tcl = -par()$mgp[2] * tick.length) # tcl gives the length of the ticks as proportion of line text, knowing that mgp is in text lines. So the main ticks are a 0.5 of the distance of the axis numbers by default. The sign provides the side of the tick (negative for outside of the plot region)
    if(xlog.scale == TRUE){
        par(xaxt = "n", xlog = TRUE) # suppress the x-axis label
    }else{
        par(xlog = FALSE)
    }
    if(ylog.scale == TRUE){
        par(yaxt = "n", ylog = TRUE) # suppress the y-axis label
    }else{
        par(ylog = FALSE)
    }
    if(return.par == TRUE){
        tempo.par <- par()
        return(tempo.par)
    }
Gael  MILLOT's avatar
Gael MILLOT committed
2906
2907
2908
}


Gael  MILLOT's avatar
Gael MILLOT committed
2909
2910
2911
######## fun_scale() #### select nice label numbers when setting number of ticks on an axis


Gael  MILLOT's avatar
Gael MILLOT committed
2912