cute_little_functions.R 112 KB
Newer Older
Gael  MILLOT's avatar
Gael MILLOT committed
1 2
################################################################
##                                                            ##
Gael  MILLOT's avatar
Gael MILLOT committed
3
##     CUTE LITTLE FUNCTIONS v1.3                             ##
Gael  MILLOT's avatar
Gael MILLOT committed
4 5 6 7 8 9 10 11 12
##                                                            ##
##     Gael A. Millot                                         ##
##                                                            ##
##     Compatible with R v3.5.1                               ##
##                                                            ##
################################################################



13
# BEWARE: do not forget to save the modifications in the .R file
Gael  MILLOT's avatar
Gael MILLOT committed
14

Gael  MILLOT's avatar
Gael MILLOT committed
15

Gael  MILLOT's avatar
Gael MILLOT committed
16 17 18 19 20
################################ OUTLINE ################################


################ Object analysis    1
######## fun_param_check() #### Checking class, type, length, etc. of objects   1
Gael  MILLOT's avatar
Gael MILLOT committed
21
######## fun_object_info() #### Recovering object information   7
Gael  MILLOT's avatar
Gael MILLOT committed
22 23
######## fun_1D_comp() #### comparison of two 1D datasets (vectors, factors, 1D tables) 7
######## fun_2D_comp() #### comparison of two 2D datasets (row & col names, dimensions, etc.)   11
Gael  MILLOT's avatar
Gael MILLOT committed
24
######## fun_list_comp() #### comparison of two lists   16
Gael  MILLOT's avatar
Gael MILLOT committed
25

Gael  MILLOT's avatar
Gael MILLOT committed
26 27 28
################ Object modification    18
######## fun_dataframe_flipping() #### flipping a data frame to have column name as a qualitative column and vice-versa 18
######## fun_refactorization() #### remove classes that are not anymore present in factors or factor columns in data frames 20
Gael  MILLOT's avatar
Gael MILLOT committed
29 30
######## fun_rounding() #### Rounding number if decimal present 22
######## fun_90clock_matrix_rot() #### 90° clockwise matrix rotation    23
Gael  MILLOT's avatar
Gael MILLOT committed
31
######## fun_hexa_hsv_color_matrix() #### Conversion of a numeric matrix into hexadecimal color matrix  23
Gael  MILLOT's avatar
Gael MILLOT committed
32

Gael  MILLOT's avatar
Gael MILLOT committed
33 34 35 36 37 38
################ Graphics   26
######## fun_window_width_resizing() #### window width depending on classes to plot 26
######## fun_open_window() #### Open a GUI or pdf graphic window    27
######## fun_graph_param_prior_plot() #### Graph param before plotting  30
######## fun_feature_post_plot() #### Graph param after plotting    33
######## fun_close_specif_window() #### Closing specific graphic windows    41
Gael  MILLOT's avatar
Gael MILLOT committed
39

Gael  MILLOT's avatar
Gael MILLOT committed
40 41
################ Exporting results (text & tables)  42
######## fun_export_data() #### Print string or data object into output file    42
Gael  MILLOT's avatar
Gael MILLOT committed
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84


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


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


######## fun_param_check() #### Checking class, type, length, etc. of objects


# Check OK: clear to go Apollo
fun_param_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){
# 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 even if it is an integer?
# 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
# 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
# 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?
# 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_param_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_param_check(data = test, print = TRUE, class = "numeric", typeof = NULL, double.as.integer.allowed = FALSE)
Gael  MILLOT's avatar
Gael MILLOT committed
85
# DEBUGGING
Gael  MILLOT's avatar
Gael MILLOT committed
86 87
# data = 1:3 ; data.name = NULL ; print = TRUE; options = NULL ; all.options.in.data = FALSE ; class = "numeric" ; typeof = NULL ; mode = NULL ; prop = NULL ; double.as.integer.allowed = TRUE ; length = NULL # for function debugging
# argument checking
Gael  MILLOT's avatar
Gael MILLOT committed
88
# source("C:/Users/Gael/Documents/Sources/debugging_tools_for_r_dev-v1.2/r_debugging_tools-v1.2.R") ; eval(parse(text = str_basic_arg_check_dev))
Gael  MILLOT's avatar
Gael MILLOT committed
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
if( ! is.null(data.name)){
if( ! (length(data.name) == 1 & class(data.name) == "character")){
tempo.cat <- paste0("\n\n================\n\nERROR: 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: 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: 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: 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: 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("logical", "integer", "numeric", "complex", "character", "matrix", "array", "data.frame", "list", "factor", "table", "expression", "name", "symbol", "function") & 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: class ARGUMENT MUST BE ONE OF THESE VALUE:\n\"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("numeric", "matrix", "array", "data.frame", "table"))){
tempo.cat <- paste0("\n\n================\n\nERROR: class ARGUMENT CANNOT BE OTHER THAN \"numeric\", \"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: 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: 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: 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: 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: 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: 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("numeric", "matrix", "array", "data.frame", "table"))){
tempo.cat <- paste0("\n\n================\n\nERROR: class ARGUMENT CANNOT BE OTHER THAN \"numeric\", \"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: 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: 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: THE double.as.integer.allowed ARGUMENT MUST BE TRUE OR FALSE ONLY\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: all.options.in.data ARGUMENT MUST BE A SINGLE LOGICAL VALUE (TRUE OR FALSE ONLY)\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: THE na.contain ARGUMENT MUST BE TRUE OR FALSE ONLY\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: THE print ARGUMENT MUST BE TRUE OR FALSE ONLY\n\n================\n\n")
stop(tempo.cat)
}
# end argument checking
if(is.null(data.name)){
data.name <- deparse(substitute(data))
}
problem <- FALSE
text <- paste0("NO PROBLEM DETECTED FOR THE ", data.name, " PARAMETER")
if( ! is.null(options)){
text <- ""
if( ! all(data %in% options)){
problem <- TRUE
text <- paste0("PROBLEM: 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("PROBLEM: 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, "\nPROBLEM: 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("PROBLEM: THE LENGTH OF ", data.name, " MUST BE ", length, " AND NOT ", length(data))
}else{
text <- paste0(text, "\nPROBLEM: THE LENGTH OF ", data.name, " MUST BE ", length, " AND NOT ", length(data))
}
}
}
if(text == ""){
text <- paste0("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 <- '
problem <- TRUE ;
if(identical(text, paste0("NO PROBLEM DETECTED FOR THE ", data.name, " PARAMETER"))){
text <- paste0("PROBLEM: THE ", data.name, " PARAMETER MUST BE ") ;
}else{
text <- paste0(text, " AND "); 
}
text <- paste0(text, toupper(arg.names[i2]), " ", get(arg.names[i2]))
'
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(eval(parse(text = paste0(arg.names[i2], "(data)"))) != get(arg.names[i2])){
eval(parse(text = tempo.script)) # execute tempo.script
}
}
}
}
if( ! is.null(prop)){
if(prop == TRUE){
if(any(data < 0 | data > 1, na.rm = TRUE)){
problem <- TRUE
if(identical(text, paste0("NO PROBLEM DETECTED FOR THE ", data.name, " PARAMETER"))){
text <- paste0("PROBLEM: ")
}else{
text <- paste0(text, " AND ")
}
text <- paste0(text, "THE ", data.name, " PARAMETER MUST BE DECIMAL VALUES BETWEEN 0 AND 1")
}
}
}
if(na.contain == FALSE & any(is.na(data)) == TRUE){
problem <- TRUE
if(identical(text, paste0("NO PROBLEM DETECTED FOR THE ", data.name, " PARAMETER"))){
text <- paste0("PROBLEM: ")
}else{
text <- paste0(text, " AND ")
}
text <- paste0(text, "THE ", data.name, " PARAMETER CONTAINS NA WHILE NOT AUTHORIZED (na.contain ARGUMENT SET TO FALSE)")
}
if(neg.values == FALSE){
if(any(data < 0, na.rm = TRUE)){
problem <- TRUE
if(identical(text, paste0("NO PROBLEM DETECTED FOR THE ", data.name, " PARAMETER"))){
text <- paste0("PROBLEM: ")
}else{
text <- paste0(text, " AND ")
}
text <- paste0(text, "THE ", data.name, " PARAMETER MUST NON NEGATIVE NUMERIC VALUES")
}
}
if(print == TRUE & problem == TRUE){
cat(paste0("\n\n================\n\n", text, "\n\n================\n\n"))
}
output <- list(problem = problem, text = text, param.name = data.name)
return(output)
}


######## fun_object_info() #### Recovering object information


# Check OK: clear to go Apollo
fun_object_info <- function(data){
# AIM:
# provide info for a single object
# REQUIRED FUNCTIONS
# none
# ARGUMENTS
# data: object to test
# RETURN
# a list containing the info
# EXAMPLES
# fun_object_info(data = 1:3)
Gael  MILLOT's avatar
Gael MILLOT committed
304 305 306 307
# DEBUGGING
# data = NULL # for function debugging
# data = 1:3 # for function debugging
# data = matrix(1:3) # for function debugging
Gael  MILLOT's avatar
Gael MILLOT committed
308
# data = data.frame(a = 1:3) # for function debugging
Gael  MILLOT's avatar
Gael MILLOT committed
309 310
# data = factor(1:3) # for function debugging
# data = list(1:3) # for function debugging
Gael  MILLOT's avatar
Gael MILLOT committed
311 312 313
# argument checking
# source("C:/Users/Gael/Documents/Sources/debugging_tools_for_r_dev-v1.2/r_debugging_tools-v1.2.R") ; eval(parse(text = str_basic_arg_check_dev)) # to check arguments status and if they have been checked using fun_param_check()
# end argument checking
Gael  MILLOT's avatar
Gael MILLOT committed
314 315 316 317
data.name <- deparse(substitute(data))
output <- list("FILE_NAME" = data.name)
tempo <- list("FILE_HEAD" = head(data))
output <- c(output, tempo)
Gael  MILLOT's avatar
Gael MILLOT committed
318
if( ! is.null(data)){
Gael  MILLOT's avatar
Gael MILLOT committed
319 320
tempo <- list("FILE_TAIL" = tail(data))
output <- c(output, tempo)
Gael  MILLOT's avatar
Gael MILLOT committed
321
if( ! is.null(dim(data))){
Gael  MILLOT's avatar
Gael MILLOT committed
322 323 324
tempo <- list("FILE_DIMENSION" = dim(data))
names(tempo[[1]]) <- c("NROW", "NCOL")
output <- c(output, tempo)
Gael  MILLOT's avatar
Gael MILLOT committed
325
}
Gael  MILLOT's avatar
Gael MILLOT committed
326 327
tempo <- list("SUMMARY" = summary(data))
output <- c(output, tempo)
Gael  MILLOT's avatar
Gael MILLOT committed
328
}
Gael  MILLOT's avatar
Gael MILLOT committed
329 330 331 332 333
if(class(data) == "data.frame" | class(data) == "matrix"){
tempo <- list("COLUM_NAMES" = names(data))
output <- c(output, tempo)
}
if(class(data) == "data.frame"){
Gael  MILLOT's avatar
Gael MILLOT committed
334 335
tempo <- list("STRUCTURE" = ls.str(data))
output <- c(output, tempo)
Gael  MILLOT's avatar
Gael MILLOT committed
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
tempo <- list("COLUMN_TYPE" = sapply(data, FUN = "typeof"))
output <- c(output, tempo)
}
if(class(data) == "list"){
tempo <- list("COMPARTMENT_NAMES" = names(data))
output <- c(output, tempo)
}
return(output)
}


######## fun_1D_comp() #### comparison of two 1D datasets (vectors, factors, 1D tables)


# Check OK: clear to go Apollo
fun_1D_comp <- function(data1, data2){
# AIM:
# compare two 1D dataset (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
# same elements
# same element names
# REQUIRED FUNCTIONS
# 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)
Gael  MILLOT's avatar
Gael MILLOT committed
373
# $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
Gael  MILLOT's avatar
Gael MILLOT committed
374 375 376 377 378
# $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
Gael  MILLOT's avatar
Gael MILLOT committed
379
# $common.names: common element names between data1 and data2 (can be a subset of $name or not). NULL if no common element names
Gael  MILLOT's avatar
Gael MILLOT committed
380 381 382
# $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
Gael  MILLOT's avatar
Gael MILLOT committed
383
# $common.elements: common elements between data1 and data2. NULL if no common elements
Gael  MILLOT's avatar
Gael MILLOT committed
384 385 386 387 388
# $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)
Gael  MILLOT's avatar
Gael MILLOT committed
389
# obs1 = 1:5 ; obs2 = 3:6 ; names(obs1) <- LETTERS[1:5] ; names(obs2) <- LETTERS[1:4] ; fun_1D_comp(obs1, obs2)
Gael  MILLOT's avatar
Gael MILLOT committed
390 391 392 393 394 395 396
# 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)
Gael  MILLOT's avatar
Gael MILLOT committed
397
# DEBUGGING
Gael  MILLOT's avatar
Gael MILLOT committed
398 399
# data1 = 1:5 ; data2 = 1:5 ; names(data1) <- LETTERS[1:5] ; names(data2) <- LETTERS[1:5] # for function debugging
# argument checking
Gael  MILLOT's avatar
Gael MILLOT committed
400
# source("C:/Users/Gael/Documents/Sources/debugging_tools_for_r_dev-v1.2/r_debugging_tools-v1.2.R") ; eval(parse(text = str_basic_arg_check_dev)) # to check arguments status and if they have been checked using fun_param_check()
Gael  MILLOT's avatar
Gael MILLOT committed
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
if( ! any(class(data1) %in% c("logical", "integer", "numeric", "character", "factor", "table"))){
tempo.cat <- paste0("\n\n================\n\nERROR: 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: 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: 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: THE data2 ARGUMENT MUST BE A 1D TABLE\n\n================\n\n")
stop(tempo.cat)
}
}
# end argument checking
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
Gael  MILLOT's avatar
Gael MILLOT committed
429
common.levels <- NULL
Gael  MILLOT's avatar
Gael MILLOT committed
430 431 432 433 434
same.name <- NULL
name <- NULL
any.id.name <- NULL
same.name.pos1 <- NULL
same.name.pos2 <- NULL
Gael  MILLOT's avatar
Gael MILLOT committed
435
common.names <- NULL
Gael  MILLOT's avatar
Gael MILLOT committed
436 437 438
any.id.element <- NULL
same.element.pos1 <- NULL
same.element.pos2 <- NULL
Gael  MILLOT's avatar
Gael MILLOT committed
439
common.elements <- NULL
Gael  MILLOT's avatar
Gael MILLOT committed
440 441 442 443 444 445 446 447 448 449 450 451 452
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))
Gael  MILLOT's avatar
Gael MILLOT committed
453
common.levels <- levels(data1)
Gael  MILLOT's avatar
Gael MILLOT committed
454 455 456 457 458 459 460
}
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)
Gael  MILLOT's avatar
Gael MILLOT committed
461
common.names <- names(data1)
Gael  MILLOT's avatar
Gael MILLOT committed
462 463 464 465
}
any.id.element <- TRUE
same.element.pos1 <- 1:length(data1)
same.element.pos2 <- 1:length(data2)
Gael  MILLOT's avatar
Gael MILLOT committed
466
common.elements <- data1
Gael  MILLOT's avatar
Gael MILLOT committed
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
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))
}
Gael  MILLOT's avatar
Gael MILLOT committed
499 500 501
if(any.id.levels == TRUE){
common.levels <- unique(c(levels(data1)[same.levels.pos1], levels(data2)[same.levels.pos2]))
}
Gael  MILLOT's avatar
Gael MILLOT committed
502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
}
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))
}
Gael  MILLOT's avatar
Gael MILLOT committed
525 526 527
if(any.id.name == TRUE){
common.names <- unique(c(names(data1)[same.name.pos1], names(data2)[same.name.pos2]))
}
Gael  MILLOT's avatar
Gael MILLOT committed
528 529 530 531 532 533 534 535 536 537
}
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)
}
Gael  MILLOT's avatar
Gael MILLOT committed
538 539 540
if(any.id.element == TRUE){
common.elements <- unique(c(data1[same.element.pos1], data2[same.element.pos2]))
}
Gael  MILLOT's avatar
Gael MILLOT committed
541 542 543 544 545 546 547 548 549 550 551 552
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
}
}
Gael  MILLOT's avatar
Gael MILLOT committed
553
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)
Gael  MILLOT's avatar
Gael MILLOT committed
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
return(output)
}


######## fun_2D_comp() #### comparison of two 2D datasets (row & col names, dimensions, etc.)


# Check OK: clear to go Apollo
fun_2D_comp <- function(data1, data2){
# AIM:
# compare two 2D dataset of the same class or not. Check and report in a list if the 2 datasets have:
# same row names
# same column names
# same row number
# same column number
# potential identical rows between the 2 datasets
# potential identical columns between the 2 datasets
# REQUIRED FUNCTIONS
# 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 ?
# $row.name: name of rows of the 2 datasets if identical (NULL otherwise)
# $same.col.name: logical. Are column names identical ?
# $col.name: name of columns of the 2 datasets if identical (NULL otherwise)
# $any.id.row: logical. is there identical rows ?
# $same.row.pos1: position, in data1, of the rows identical in data2
# $same.row.pos2: position, in data2, of the rows identical in data1
# $any.id.col: logical. is there identical columns ?
# $same.col.pos1: position in data1 of the cols identical in data2
# $same.col.pos2: position in data2 of the cols identical in data1
# $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]))) ; fun_2D_comp(obs1, obs2)
Gael  MILLOT's avatar
Gael MILLOT committed
600
# DEBUGGING
Gael  MILLOT's avatar
Gael MILLOT committed
601 602 603 604 605 606 607 608 609 610 611
# 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: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 = 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
# argument checking
Gael  MILLOT's avatar
Gael MILLOT committed
612
# source("C:/Users/Gael/Documents/Sources/debugging_tools_for_r_dev-v1.2/r_debugging_tools-v1.2.R") ; eval(parse(text = str_basic_arg_check_dev)) # to check arguments status and if they have been checked using fun_param_check()
Gael  MILLOT's avatar
Gael MILLOT committed
613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836
if( ! any(class(data1) %in% c("matrix", "data.frame", "table"))){
tempo.cat <- paste0("\n\n================\n\nERROR: 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: THE data2 ARGUMENT MUST BE A MATRIX, DATA FRAME OR TABLE\n\n================\n\n")
stop(tempo.cat)
}
# end argument checking
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
same.col.name <- 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]]
same.col.name <- TRUE
col.name <- 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: 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: 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: 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 <- TRUE
same.col.name <- TRUE
# 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]]
}
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 <- suppressWarnings(which(mapply(FUN = identical, c(as.data.frame(t(data1), stringsAsFactors = FALSE)), c(as.data.frame(t(data2), stringsAsFactors = FALSE)))))
same.row.pos2 <- suppressWarnings(which(mapply(FUN = identical, c(as.data.frame(t(data2), stringsAsFactors = FALSE)), 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 <- suppressWarnings(which(mapply(FUN = identical, c(data1), c(data2))))
same.col.pos2 <- suppressWarnings(which(mapply(FUN = identical, c(data2), 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
}
}
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, same.col.name = same.col.name, col.name = col.name, 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)
}


######## fun_list_comp() #### comparison of two lists


# Check OK: clear to go Apollo
fun_list_comp <- function(data1, data2){
# AIM:
# compare two lists. Check and report in a list if the 2 datasets have:
#same length
# same names
# same compartments
# REQUIRED FUNCTIONS
# 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)
Gael  MILLOT's avatar
Gael MILLOT committed
837
# DEBUGGING
Gael  MILLOT's avatar
Gael MILLOT committed
838 839 840
# 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
# argument checking
Gael  MILLOT's avatar
Gael MILLOT committed
841
# source("C:/Users/Gael/Documents/Sources/debugging_tools_for_r_dev-v1.2/r_debugging_tools-v1.2.R") ; eval(parse(text = str_basic_arg_check_dev)) # to check arguments status and if they have been checked using fun_param_check()
Gael  MILLOT's avatar
Gael MILLOT committed
842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950
if( ! any(class(data1) %in% "list")){
tempo.cat <- paste0("\n\n================\n\nERROR: 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: THE data2 ARGUMENT MUST BE A LIST\n\n================\n\n")
stop(tempo.cat)
}
# end argument checking
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)
}


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


######## fun_dataframe_flipping() #### flipping a data frame to have column name as a qualitative column and vice-versa


# Check OK: clear to go Apollo
fun_dataframe_flipping <- function(data, quanti.col.name = "quanti", quali.col.name = "quali"){
# AIM:
# if the data frame is made of numeric columns, a new data frame is created, with the 1st column gathering all the numeric values, and the 2nd column being the name of the columns of the initial data frame. If 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
# REQUIRED FUNCTIONS
# fun_param_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(a = 1:3, b = c("A", "B", "A")) ; fun_dataframe_flipping(obs)
# obs <- data.frame(a = 1:3, b = c("A", "B", "A")) ; fun_dataframe_flipping(obs, quanti.col.name = "quanti", quali.col.name = "quali")
# obs <- data.frame(a = 1:3, b = 4:6) ; fun_dataframe_flipping(obs)
Gael  MILLOT's avatar
Gael MILLOT committed
951
# DEBUGGING
Gael  MILLOT's avatar
Gael MILLOT committed
952 953 954 955 956 957 958 959
# 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
# argument checking
arg.check <- NULL # for function debbuging
Gael  MILLOT's avatar
Gael MILLOT committed
960 961
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))
Gael  MILLOT's avatar
Gael MILLOT committed
962 963 964 965 966
tempo <- fun_param_check(data = quanti.col.name, class = "character", length = 1) ; eval(ee)
tempo <- fun_param_check(data = quali.col.name, class = "character", length = 1) ; eval(ee)
if(any(arg.check) == TRUE){
stop()
}
Gael  MILLOT's avatar
Gael MILLOT committed
967
# source("C:/Users/Gael/Documents/Sources/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_param_check_dev)) # to check arguments status and if they have been checked using fun_param_check()
Gael  MILLOT's avatar
Gael MILLOT committed
968 969
if( ! any(class(data) %in% "data.frame")){
tempo.cat <- paste0("\n\n================\n\nERROR: THE data ARGUMENT MUST BE A DATA FRAME\n\n================\n\n")
Gael  MILLOT's avatar
Gael MILLOT committed
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 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
stop(tempo.cat)
}
# end argument checking
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: 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: 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: 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: NUMERIC DATA FRAME in the data ARGUMENT MUST HAVE COLUMN NAMES\n\n================\n\n")
stop()
}
if(all(tempo.factor %in% "numeric")){
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)
}else{
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)
}


######## fun_refactorization() #### remove classes that are not anymore present in factors or factor columns in data frames


# Check OK: clear to go Apollo
fun_refactorization <- function(data, also.ordered = TRUE){
# AIM:
# refactorize a factor or the factor columns of a data frame, such as only the class present are in the levels (no empty levels). The class order in levels is kept
# useful to remove the empty classes after row removing for instance
# REQUIRED FUNCTIONS
# fun_param_check()
# ARGUMENTS
# data: factor (ordered or not) or data frame
# also.ordered: refactorize also ordered factors? This to deal with ordered factors that have class "ordered" "factor"
# RETURN
# a list containing:
# $data: the modified object
# $removed: the removed classes for a factor and a list of the removed classes for each factor class of the data frame
# EXAMPLES
# obs <- data.frame(a = LETTERS[1:6], b = paste0(letters[1.6], c(1,1,2,2,3,3)), c = ordered(LETTERS[7:12]), d = 1:6)[-c(1:2),] ; fun_refactorization(obs, FALSE)
# obs <- data.frame(a = LETTERS[1:6], b = paste0(letters[1.6], c(1,1,2,2,3,3)), c = ordered(LETTERS[7:12]), d = 1:6)[-c(1:2),] ; fun_refactorization(obs, TRUE)
# obs <- factor(LETTERS[1:6])[-c(1:2)] ; fun_refactorization(obs, TRUE)
# obs <- ordered(LETTERS[1:6])[-c(1:2)] ; fun_refactorization(obs, TRUE)
# obs <- factor(LETTERS[1:6], levels = rev(LETTERS[1:6]))[-c(1:2)] ; fun_refactorization(obs, FALSE)
Gael  MILLOT's avatar
Gael MILLOT committed
1044
# DEBUGGING
Gael  MILLOT's avatar
Gael MILLOT committed
1045 1046 1047 1048 1049
# data <- data.frame(a = LETTERS[1:6], b = paste0(letters[1.6], c(1,1,2,2,3,3)), c = ordered(LETTERS[7:12]), d = 1:6) ; data <- data[-c(1:2),] ; also.ordered <- TRUE # for function debugging
# data <- factor(LETTERS[1:6])[-c(1:2)] ; also.ordered <- TRUE # for function debugging
# data <- ordered(LETTERS[1:6])[-c(1:2)] ; also.ordered <- TRUE # for function debugging
# argument checking
arg.check <- NULL # for function debbuging
Gael  MILLOT's avatar
Gael MILLOT committed
1050 1051
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))
Gael  MILLOT's avatar
Gael MILLOT committed
1052 1053 1054 1055
tempo <- fun_param_check(data = also.ordered, class = "logical", length = 1) ; eval(ee)
if(any(arg.check) == TRUE){
stop()
}
Gael  MILLOT's avatar
Gael MILLOT committed
1056
# source("C:/Users/Gael/Documents/Sources/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_param_check_dev)) # to check arguments status and if they have been checked using fun_param_check()
Gael  MILLOT's avatar
Gael MILLOT committed
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130
if(also.ordered == FALSE){
if( ! (all(class(data) == "data.frame") | all(class(data) == "factor"))){
tempo.cat <- paste0("\n\n================\n\nERROR: data ARGUMENT MUST BE A FACTOR (NON ORDERED BECAUSE THE also.ordered ARGUMENT IS SET TO FALSE) OR A DATA FRAME\n\n================\n\n")
stop(tempo.cat)
}
}
if(also.ordered == TRUE){
if( ! (all(class(data) == "data.frame") | all(class(data) == "factor") | all(class(data) %in% c("ordered", "factor")))){
tempo.cat <- paste0("\n\n================\n\nERROR: data ARGUMENT MUST BE A FACTOR OR A DATA FRAME\n\n================\n\n")
stop(tempo.cat)
}
}
# end argument checking
text <- NULL
if(all(class(data) == "factor")){
tempo.keep.log <- levels(data) %in% unique(data)
if(any(tempo.factor.col == TRUE)){
text <- levels(data)[ ! tempo.keep.log]
data <- factor(data, levels = levels(data)[tempo.keep.log])
}
}else if(all(class(data) %in% c("ordered", "factor"))){
tempo.keep.log <- levels(data) %in% unique(data)
if(any(tempo.factor.col == TRUE)){
text <- levels(data)[ ! tempo.keep.log]
data <- ordered(data, levels = levels(data)[tempo.keep.log])
}
}else if(all(class(data) == "data.frame")){
text <- vector("list", length(data))
names(text) <- names(data)
tempo.factor.col <- sapply(sapply(lapply(data, class), FUN = "%in%", "factor"), FUN = "all") # get the factor column (logical)
for(i in 1:length(tempo.factor.col)){
if(tempo.factor.col[i] == TRUE){
tempo.keep.log <- levels(data[[i]]) %in% unique(data[[i]])
text[[i]] <- levels(data[[i]])[ ! tempo.keep.log]
data[[i]] <- factor(data[[i]], levels = levels(data[[i]])[tempo.keep.log])
}
}
if(also.ordered == TRUE){
tempo.ordered.col <- sapply(sapply(lapply(data, class), FUN = "%in%", "ordered"), FUN = "any") # get the ordered factor column (logical)
for(i in 1:length(tempo.ordered.col)){
if(tempo.ordered.col[i] == TRUE){
tempo.keep.log <- levels(data[[i]]) %in% unique(data[[i]])
text[[i]] <- levels(data[[i]])[ ! tempo.keep.log]
data[[i]] <- ordered(data[[i]], levels = levels(data[[i]])[tempo.keep.log])
}
}
}
}
output <- list(data = data, removed = text)
return(output)
}


######## fun_rounding() #### Rounding number if decimal present


# Check OK: clear to go Apollo
fun_rounding <- function(data, dec.nb = 2, after.lead.zero = TRUE){
# AIM:
# round a vector of value, if decimal, with the desired number of decimal digits after the decimal leading zeros
# BEWARE
# 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
# 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
# fun_param_check()
# RETURN
# the modified vector
# EXAMPLES
# fun_rounding(data = c(10, 100.001, 333.0001254, 12312.1235), dec.nb = 2, after.lead.zero = FALSE)
# fun_rounding(data = c("10", "100.001", "333.0001254", "12312.1235"), dec.nb = 2, after.lead.zero = FALSE)
Gael  MILLOT's avatar
Gael MILLOT committed
1131
# DEBUGGING
Gael  MILLOT's avatar
Gael MILLOT committed
1132 1133 1134 1135 1136 1137 1138 1139
# 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
# argument checking
if( ! (all(typeof(data) == "character") | all(typeof(data) == "double") | all(typeof(data) == "integer"))){
tempo.cat <- paste0("\n\n================\n\nERROR: data ARGUMENT MUST BE A VECTOR OF NUMBERS (IN NUMERIC OR CHARACTER MODE)\n\n================\n\n")
stop(tempo.cat)
}
arg.check <- NULL # for function debbuging
Gael  MILLOT's avatar
Gael MILLOT committed
1140 1141
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))
Gael  MILLOT's avatar
Gael MILLOT committed
1142 1143 1144 1145 1146
tempo <- fun_param_check(data = dec.nb, typeof = "integer", length = 1, double.as.integer.allowed = TRUE, neg.values = FALSE) ; eval(ee)
tempo <- fun_param_check(data = after.lead.zero, class = "logical", length = 1) ; eval(ee)
if(any(arg.check) == TRUE){
stop()
}
Gael  MILLOT's avatar
Gael MILLOT committed
1147
# source("C:/Users/Gael/Documents/Sources/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_param_check_dev)) # to check arguments status and if they have been checked using fun_param_check()
Gael  MILLOT's avatar
Gael MILLOT committed
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
# end argument checking
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)
}


######## fun_90clock_matrix_rot() #### 90° clockwise matrix rotation


# Check OK: clear to go Apollo
fun_90clock_matrix_rot <- function(data){
# AIM:
# 90° clockwise matrix rotation
# applied twice, the function provide the mirror matrix, according to vertical and horizontal symmetry
# REQUIRED FUNCTIONS
# fun_param_check()
# ARGUMENTS
# data: matrix (matrix class)
# RETURN
# the modified matrix
# EXAMPLES
Gael  MILLOT's avatar
Gael MILLOT committed
1191 1192
# obs <- matrix(1:10, ncol = 1) ; obs ; fun_90clock_matrix_rot(obs)
# obs <- matrix(LETTERS[1:10], ncol = 5) ; obs ; fun_90clock_matrix_rot(obs)
Gael  MILLOT's avatar
Gael MILLOT committed
1193 1194
# DEBUGGING
# data = matrix(1:10, ncol = 1)
Gael  MILLOT's avatar
Gael MILLOT committed
1195
# argument checking
Gael  MILLOT's avatar
Gael MILLOT committed
1196
# source("C:/Users/Gael/Documents/Sources/debugging_tools_for_r_dev-v1.2/r_debugging_tools-v1.2.R") ; eval(parse(text = str_basic_arg_check_dev)) # to check arguments status and if they have been checked using fun_param_check()
Gael  MILLOT's avatar
Gael MILLOT committed
1197 1198
if( ! any(class(data) %in% "matrix")){
tempo.cat <- paste0("\n\n================\n\nERROR: THE data ARGUMENT MUST BE A MATRIX\n\n================\n\n")
Gael  MILLOT's avatar
Gael MILLOT committed
1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229
stop(tempo.cat)
}
# end argument checking
for (i in 1:ncol(data)){data[,i] <- rev(data[,i])}
data <- t(data)
return(data)
}


######## fun_hexa_hsv_color_matrix() #### Conversion of a numeric matrix into hexadecimal color matrix


# Check OK: clear to go Apollo
fun_hexa_hsv_color_matrix <- function(mat1, mat.hsv.h = TRUE, notch = 1, s = 1, v = 1, forced.color = NULL){
# AIM:
# convert a matrix made of number into a hexadecimal matrix for rgb colorization
# REQUIRED FUNCTIONS
# fun_param_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
Gael  MILLOT's avatar
Gael MILLOT committed
1230
# EXAMPLES
Gael  MILLOT's avatar
Gael MILLOT committed
1231
# mat1 = matrix(c(1,1,1,2,1,5,9,NA), ncol = 2) ; dimnames(mat1) <- list(LETTERS[1:4], letters[1:2]) ; fun_hexa_hsv_color_matrix(mat1, mat.hsv.h = FALSE, notch = 1, s = 1, v = 1, forced.color = NULL)
Gael  MILLOT's avatar
Gael MILLOT committed
1232
# DEBUGGING
Gael  MILLOT's avatar
Gael MILLOT committed
1233 1234 1235
# 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
# argument checking
arg.check <- NULL # for function debbuging
Gael  MILLOT's avatar
Gael MILLOT committed
1236 1237
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))
Gael  MILLOT's avatar
Gael MILLOT committed
1238 1239 1240 1241 1242 1243 1244 1245
tempo <- fun_param_check(data = mat1, mode = "numeric", class = "matrix", na.contain = TRUE, neg.values = FALSE) ; eval(ee)
tempo <- fun_param_check(data = mat.hsv.h, class = "logical", length = 1) ; eval(ee)
tempo <- fun_param_check(data = notch, mode = "numeric", length = 1, prop = TRUE) ; eval(ee)
tempo <- fun_param_check(data = s, mode = "numeric", length = 1, prop = TRUE) ; eval(ee)
tempo <- fun_param_check(data = v, mode = "numeric", length = 1, prop = TRUE) ; eval(ee)
if(any(arg.check) == TRUE){
stop()
}
Gael  MILLOT's avatar
Gael MILLOT committed
1246
# source("C:/Users/Gael/Documents/Sources/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_param_check_dev)) # to check arguments status and if they have been checked using fun_param_check()
Gael  MILLOT's avatar
Gael MILLOT committed
1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 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
if(mat.hsv.h == TRUE & fun_param_check(data = mat1, mode = "numeric", prop = TRUE, print = FALSE)$problem == TRUE){
tempo.cat <- paste0("\n\n================\n\nERROR: 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_param_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: 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
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: 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: 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: 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: 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: 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)
}


################ Graphics


# this order can be used:
# fun_window_width_resizing()
# fun_open_window()
# fun_graph_param_prior_plot() # not for ggplot2
# plot() or any other plotting
# fun_feature_post_plot() if fun_graph_param_prior_plot() has been used # not for ggplot2
# fun_close_specif_window()


######## fun_window_width_resizing() #### window width depending on classes to plot


# Check OK: clear to go Apollo
fun_window_width_resizing <- function(class.nb, inches.per.class.nb = 1, ini.window.width = 7, inch.left.space, inch.right.space, boundarie.space = 0.5){
# 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_window_width_resizing()
# fun_open_window()
# fun_graph_param_prior_plot() # not for ggplot2
# plot() or any other plotting
# fun_feature_post_plot() if fun_graph_param_prior_plot() has been used # not for ggplot2
# fun_close_specif_window()
# REQUIRED FUNCTIONS
# fun_param_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_window_width_resizing(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)
Gael  MILLOT's avatar
Gael MILLOT committed
1361
# DEBUGGING
Gael  MILLOT's avatar
Gael MILLOT committed
1362 1363 1364
# 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
# argument checking
arg.check <- NULL # for function debbuging
Gael  MILLOT's avatar
Gael MILLOT committed
1365 1366
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))
Gael  MILLOT's avatar
Gael MILLOT committed
1367 1368 1369 1370 1371 1372 1373 1374 1375
tempo <- fun_param_check(data = class.nb, typeof = "integer", length = 1, double.as.integer.allowed = TRUE, neg.values = FALSE) ; eval(ee)
tempo <- fun_param_check(data = inches.per.class.nb, mode = "numeric", length = 1, neg.values = FALSE) ; eval(ee)
tempo <- fun_param_check(data = ini.window.width, mode = "numeric", length = 1, neg.values = FALSE) ; eval(ee)
tempo <- fun_param_check(data = inch.left.space, mode = "numeric", length = 1, neg.values = FALSE) ; eval(ee)
tempo <- fun_param_check(data = inch.right.space, mode = "numeric", length = 1, neg.values = FALSE) ; eval(ee)
tempo <- fun_param_check(data = boundarie.space, mode = "numeric", length = 1, neg.values = FALSE) ; eval(ee)
if(any(arg.check) == TRUE){
stop()
}
Gael  MILLOT's avatar
Gael MILLOT committed
1376
# source("C:/Users/Gael/Documents/Sources/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_param_check_dev)) # to check arguments status and if they have been checked using fun_param_check()
Gael  MILLOT's avatar
Gael MILLOT committed
1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415
# end argument checking
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)
}


######## fun_open_window() #### Open a GUI or pdf graphic window


# Check OK: clear to go Apollo
fun_open_window <- 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){
# 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_window_width_resizing()
# fun_open_window()
# fun_graph_param_prior_plot() # not for ggplot2
# plot() or any other plotting
# fun_feature_post_plot() if fun_graph_param_prior_plot() has been used # not for ggplot2
# fun_close_specif_window()
# REQUIRED FUNCTIONS
# fun_param_check()
# ARGUMENTS:
# pdf.disp: use pdf or not
# path.fun: where the pdf is saved. Must not finish by a path separator. 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)
Gael  MILLOT's avatar
Gael MILLOT committed
1416
# EXAMPLES
Gael  MILLOT's avatar
Gael MILLOT committed
1417
# fun_open_window(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)
Gael  MILLOT's avatar
Gael MILLOT committed
1418
# DEBUGGING
Gael  MILLOT's avatar
Gael MILLOT committed
1419 1420 1421
# 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
# argument checking
arg.check <- NULL # for function debbuging
Gael  MILLOT's avatar
Gael MILLOT committed
1422 1423
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))
Gael  MILLOT's avatar
Gael MILLOT committed
1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435
tempo <- fun_param_check(data = pdf.disp, class = "logical", length = 1) ; eval(ee)
tempo <- fun_param_check(data = path.fun, class = "character", length = 1) ; eval(ee)
tempo <- fun_param_check(data = pdf.name.file, class = "character", length = 1) ; eval(ee)
tempo <- fun_param_check(data = width.fun, mode = "numeric", length = 1, neg.values = FALSE) ; eval(ee)
tempo <- fun_param_check(data = height.fun, mode = "numeric", length = 1, neg.values = FALSE) ; eval(ee)
tempo <- fun_param_check(data = path.fun, class = "character", length = 1) ; eval(ee)
tempo <- fun_param_check(data = paper, options = c("a4", "letter", "legal", "us", "executive", "a4r", "USr", "special", "A4", "LETTER", "LEGAL", "US"), length = 1) ; eval(ee)
tempo <- fun_param_check(data =no.pdf.overwrite, class = "logical", length = 1) ; eval(ee)
tempo <- fun_param_check(data = return.output, class = "logical", length = 1) ; eval(ee)
if(any(arg.check) == TRUE){
stop()
}
Gael  MILLOT's avatar
Gael MILLOT committed
1436
# source("C:/Users/Gael/Documents/Sources/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_param_check_dev)) # to check arguments status and if they have been checked using fun_param_check()
Gael  MILLOT's avatar
Gael MILLOT committed
1437 1438 1439 1440 1441
# end argument checking
if(path.fun == "working.dir"){
path.fun <- getwd()
}else{
if(dir.exists(path.fun) == FALSE){
Gael  MILLOT's avatar
Gael MILLOT committed
1442
tempo.cat <- paste0("\n\n================\n\nERROR: path.fun ARGUMENT DOES NOT CORRESPOND TO EXISTING DIRECTORY\n\n================\n\n")
Gael  MILLOT's avatar
Gael MILLOT committed
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
stop(tempo.cat)
}
}
if(Sys.info()["sysname"] == "Windows"){ # Note that .Platform$OS.type() only says "unix" for macOS and Linux and "Windows" for Windows
tempo <- NULL
windows()
ini.par <- par(no.readonly = TRUE) # to recover the initial graphical parameters if required (reset)
invisible(dev.off()) # close the new window
}else if(Sys.info()["sysname"] == "Linux"){
if( ! file.exists(paste0(getwd(), "/Rplots.pdf"))){
tempo <- suppressWarnings(try(X11(), silent = TRUE))[] # open a X11 window or a pdf. So no need to use again X11(). tempo == NULL if no problem, meaning that the X11 window is opened. If tempo != NULL, a pdf is open here paste0(getwd(), "/Rplots.pdf")
ini.par <- par(no.readonly = TRUE) # recover the initial graphical parameters. Works even if X11 is not working as R opens a pdf
invisible(dev.off()) # can be used here to close the pdf windows if tempo != NULL and to close the X11 window if tempo == NULL
}else{
tempo.cat <- paste0("\n\n================\n\nPROBLEM: 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{
tempo <- NULL
quartz()
ini.par <- par(no.readonly = TRUE) # to recover the initial graphical parameters if required (reset)
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: pdf.loc FILE ALREADY EXISTS AND CANNOT BE OVERWRITTEN DUE TO no.pdf.overwrite ARGUMENT SET TO TRUE\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(tempo)){
stop("PROBLEM: 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")
}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)
}
}


######## fun_graph_param_prior_plot() #### Graph param before plotting


# Check OK: clear to go Apollo
fun_graph_param_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){
# AIM:
# reinitialize and set the graphic parameters before plotting
# very convenient to erase the axes for post plot axis redrawing using fun_feature_post_plot()
# REQUIRED FUNCTIONS
# fun_param_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_feature_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_feature_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_graph_param_prior_plot(param.reinitial = FALSE, xlog.scale = FALSE, ylog.scale = FALSE, remove.label = TRUE, remove.x.axis = TRUE, remove.y.axis = 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)
Gael  MILLOT's avatar
Gael MILLOT committed
1531
# DEBUGGING
Gael  MILLOT's avatar
Gael MILLOT committed
1532 1533 1534
# param.reinitial = FALSE ; xlog.scale = FALSE ; ylog.scale = FALSE ; remove.label = TRUE ; remove.x.axis = TRUE ; remove.y.axis = 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
# argument checking
arg.check <- NULL # for function debbuging
Gael  MILLOT's avatar
Gael MILLOT committed
1535 1536
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))
Gael  MILLOT's avatar
Gael MILLOT committed
1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559
tempo <- fun_param_check(data = param.reinitial, class = "logical", length = 1) ; eval(ee)
tempo <- fun_param_check(data = xlog.scale, class = "logical", length = 1) ; eval(ee)
tempo <- fun_param_check(data = ylog.scale, class = "logical", length = 1) ; eval(ee)
tempo <- fun_param_check(data = remove.label, class = "logical", length = 1) ; eval(ee)
tempo <- fun_param_check(data = remove.x.axis, class = "logical", length = 1) ; eval(ee)
tempo <- fun_param_check(data = remove.y.axis, class = "logical", length = 1) ; eval(ee)
tempo <- fun_param_check(data = std.x.range, class = "logical", length = 1) ; eval(ee)
tempo <- fun_param_check(data = std.y.range, class = "logical", length = 1) ; eval(ee)
tempo <- fun_param_check(data = down.space, class = "numeric", length = 1, neg.values = FALSE) ; eval(ee)
tempo <- fun_param_check(data = left.space, class = "numeric", length = 1, neg.values = FALSE) ; eval(ee)
tempo <- fun_param_check(data = up.space, class = "numeric", length = 1, neg.values = FALSE) ; eval(ee)
tempo <- fun_param_check(data = right.space, class = "numeric", length = 1, neg.values = FALSE) ; eval(ee)
tempo <- fun_param_check(data = orient, class = "numeric", length = 1, neg.values = FALSE) ; eval(ee)
tempo <- fun_param_check(data = dist.legend, class = "numeric", length = 1, neg.values = FALSE) ; eval(ee)
tempo <- fun_param_check(data = tick.length, class = "numeric", length = 1, prop = TRUE) ; eval(ee)
tempo <- fun_param_check(data = box.type, options = c("o", "l", "7", "c", "u", "]", "n"), length = 1) ; eval(ee)
tempo <- fun_param_check(data = amplif.label, class = "numeric", length = 1, neg.values = FALSE) ; eval(ee)
tempo <- fun_param_check(data = amplif.axis, class = "numeric", length = 1, neg.values = FALSE) ; eval(ee)
tempo <- fun_param_check(data = display.extend, class = "logical", length = 1) ; eval(ee)
tempo <- fun_param_check(data = return.par, class = "logical", length = 1) ; eval(ee)
if(any(arg.check) == TRUE){
stop()
}
Gael  MILLOT's avatar
Gael MILLOT committed
1560
# source("C:/Users/Gael/Documents/Sources/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_param_check_dev)) # to check arguments status and if they have been checked using fun_param_check()
Gael  MILLOT's avatar
Gael MILLOT committed
1561 1562
# end argument checking
if(param.reinitial == TRUE){
1563 1564 1565 1566 1567
if( ! all(names(dev.cur()) == "null device")){
active.wind.nb <- dev.cur()
}else{
active.wind.nb <- 0
}
Gael  MILLOT's avatar
Gael MILLOT committed
1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578
if(Sys.info()["sysname"] == "Windows"){ # Note that .Platform$OS.type() only says "unix" for macOS and Linux and "Windows" for Windows
windows()
}else if(Sys.info()["sysname"] == "Linux"){
if( ! file.exists(paste0(getwd(), "/Rplots.pdf"))){
tempo <- suppressWarnings(try(X11(), silent = TRUE))[] # open a X11 window or a pdf. So no need to use again X11(). tempo == NULL if no problem, meaning that the X11 window is opened. If tempo != NULL, a pdf is open here paste0(getwd(), "/Rplots.pdf")
}else{
tempo.cat <- paste0("\n\n================\n\nPROBLEM: 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{ # macOS
quartz()
1579
}
Gael  MILLOT's avatar
Gael MILLOT committed
1580 1581
ini.par <- par(no.readonly = TRUE) # to recover the initial graphical parameters if required (reset)
invisible(dev.off()) # close the new window
1582 1583
if( ! all(names(dev.cur()) == "null device")){
dev.set(active.wind.nb) # go back to the active windows if exists
Gael  MILLOT's avatar
Gael MILLOT committed
1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625
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.sca