cute_little_R_functions.R 189 KB
Newer Older
Gael  MILLOT's avatar
Gael MILLOT committed
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
            if(identical(same.compartment.pos1, same.compartment.pos2)){
                identical.content <- TRUE
            }else{
                identical.content <- FALSE
            }
        }else{
            identical.content <- FALSE
        }
    }
    output <- list(same.length = same.length, length = length, same.name = same.name, name = name, any.id.name = any.id.name, same.name.pos1 = same.name.pos1, same.name.pos2 = same.name.pos2, any.id.compartment = any.id.compartment, same.compartment.pos1 = same.compartment.pos1, same.compartment.pos2 = same.compartment.pos2, identical.object = identical.object, identical.content = identical.content)
    return(output)
Gael  MILLOT's avatar
Gael MILLOT committed
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
}


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


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


# Check OK: clear to go Apollo
fun_dataframe_remodeling <- function(data, quanti.col.name = "quanti", quali.col.name = "quali"){
Gael  MILLOT's avatar
Gael MILLOT committed
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
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
    # AIM:
    # if the data frame is made of numeric columns, a new data frame is created, with the 1st column gathering all the numeric values, and the 2nd column being the name of the columns of the initial data frame. If row names were present in the initial data frame, then a new ini_rowname column is added with the names of the rows
    
    
    # If the data frame is made of one numeric column and one character or factor column, a new data frame is created, with the new columns corresponding to the split numeric values (according to the character column). NA are added a the end of each column to have the same number of rows. BEWARE: in such data frame, rows are not individuals. This means that in the example below, values 10 and 20 are associated on the same row but that means nothing in term of association
    
    
    
    # REQUIRED FUNCTIONS
    # 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(col1 = (1:4)*10, col2 = c("A", "B", "A", "A")) ; obs ; fun_dataframe_remodeling(obs)
    # obs <- data.frame(col1 = (1:4)*10, col2 = 5:8) ; obs ; fun_dataframe_remodeling(obs, quanti.col.name = "quanti", quali.col.name = "quali")
    # obs <- data.frame(col1 = (1:4)*10, col2 = 5:8) ; rownames(obs) <- paste0("row", 1:4) ; obs ; fun_dataframe_remodeling(obs, quanti.col.name = "quanti", quali.col.name = "quali")
    # DEBUGGING
    # data = data.frame(a = 1:3, b = 4:6) ; quanti.col.name = "quanti" ; quali.col.name = "quali" # for function debugging
    # data = data.frame(a = 1:3, b = 4:6, c = 11:13) ; quanti.col.name = "quanti" ; quali.col.name = "quali" # for function debugging
    # data = data.frame(a = 1:3, b = letters[1:3]) ; quanti.col.name = "quanti" ; quali.col.name = "quali" # for function debugging
    # data = data.frame(a = 1:3, b = letters[1:3]) ; quanti.col.name = "TEST" ; quali.col.name = "quali" # for function debugging
    # data = data.frame(b = letters[1:3], a = 1:3) ; quanti.col.name = "quanti" ; quali.col.name = "quali" # for function debugging
    # data = data.frame(b = c("e", "e", "h"), a = 1:3) ; quanti.col.name = "quanti" ; quali.col.name = "quali" # for function debugging
    # required function checking
    if(length(find("fun_param_check", mode = "function")) == 0){
        tempo.cat <- paste0("\n\n================\n\nERROR IN fun_dataframe_remodeling(): REQUIRED fun_param_check() FUNCTION IS MISSING IN THE R ENVIRONMENT\n\n================\n\n")
        stop(tempo.cat)
    }
    # end required function checking
    arg.check <- NULL # for function debbuging
    checked.arg.names <- NULL # for function debbuging
    ee <- expression(arg.check <- c(arg.check, tempo$problem) , checked.arg.names <- c(checked.arg.names, tempo$param.name))
    tempo <- fun_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() # nothing else because print = TRUE by default in fun_param_check()
    }
    # source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.2/r_debugging_tools-v1.2.R") ; eval(parse(text = str_basic_arg_check_dev)) ; eval(parse(text = str_arg_check_with_fun_param_check_dev)) # activate this line and use the function to check arguments status and if they have been checked using fun_param_check()
    if( ! any(class(data) %in% "data.frame")){
        tempo.cat <- paste0("\n\n================\n\nERROR IN fun_dataframe_remodeling(): THE data ARGUMENT MUST BE A DATA FRAME\n\n================\n\n")
        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 IN fun_dataframe_remodeling(): IF data ARGUMENT IS A DATA FRAME MADE OF 2 COLUMNS, EITHER A COLUMN MUST BE NUMERIC AND THE OTHER CHARACTER, OR THE TWO COLUMNS MUST BE NUMERIC\n\n================\n\n")
            stop(tempo.cat)
        }
        if((mode(data[, 1]) == "character" | mode(data[, 2]) == "character") & (quanti.col.name != "quanti" | quali.col.name != "quali")){
            tempo.cat <- paste0("\n\n================\n\nERROR IN fun_dataframe_remodeling(): IMPROPER quanti.col.name OR quali.col.name RESETTINGS. THESE ARGUMENTS ARE RESERVED FOR DATA FRAMES MADE OF n NUMERIC COLUMNS ONLY\n\n================\n\n")
            stop(tempo.cat)
        }
    }else{
        if( ! all(tempo.factor %in% "numeric")){
            tempo.cat <- paste0("\n\n================\n\nERROR IN fun_dataframe_remodeling(): IF data ARGUMENT IS A DATA FRAME MADE OF ONE COLUMN, OR MORE THAN 2 COLUMNS, THESE COLUMNS MUST BE NUMERIC\n\n================\n\n")
            stop(tempo.cat)
        }
    }
    if(( ! any(tempo.factor %in% "character")) & is.null(names(data))){
        tempo.cat <- paste0("\n\n================\n\nERROR IN fun_dataframe_remodeling(): NUMERIC DATA FRAME in the data ARGUMENT MUST HAVE COLUMN NAMES\n\n================\n\n")
        stop()
    }
    if(all(tempo.factor %in% "numeric")){ # transfo 1
        quanti <- NULL
        for(i in 1:length(data)){
            quanti <-c(quanti, data[, i])
        }
        quali <- rep(names(data), each = nrow(data))
        output.data <- data.frame(quanti, quali)
        names(output.data) <- c(quanti.col.name, quali.col.name)
        # add the ini_rowname column
        ini.rownames <- rownames(data)
        tempo.data <- data
        rownames(tempo.data) <- NULL
        null.rownames <- (tempo.data)
        if( ! identical(ini.rownames, null.rownames)){
            ini_rowname <- rep(ini.rownames, times = ncol(data))
            output.data <- cbind(output.data, ini_rowname)
        }
    }else{ # transfo 2
        if(class(data[, 1]) == "character"){
            data <- cbind(data[2], data[1])
        }
        nc.max <- max(table(data[, 2])) # effectif maximum des classes
        nb.na <- nc.max - table(data[,2]) # nombre de NA  ajouter pour raliser 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 ajouts lorsque les effectifs sont diffrents entre les classes. C'est uniquement pour que chaque colonne ait le mme nombre de lignes
        output.data<-data.frame(tempo)
    }
    return(output.data)
Gael  MILLOT's avatar
Gael MILLOT committed
1124
1125
1126
1127
1128
1129
1130
1131
}


######## 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){
Gael  MILLOT's avatar
Gael MILLOT committed
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
    # 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, e = "A")[-c(1:2),] ; sapply(obs, levels) ; 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, e = "A")[-c(1:2),] ; sapply(obs, levels) ; fun_refactorization(obs, TRUE)
    # obs <- factor(LETTERS[1:6])[-c(1:2)] ; obs ; fun_refactorization(obs, TRUE)
    # obs <- ordered(LETTERS[1:6])[-c(1:2)] ; obs ; fun_refactorization(obs, TRUE)
    # obs <- factor(LETTERS[1:6], levels = rev(LETTERS[1:6]))[-c(1:2)] ; obs ; fun_refactorization(obs, FALSE)
    # DEBUGGING
    # 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, e = "A") ; 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
    # required function checking
    if(length(find("fun_param_check", mode = "function")) == 0){
        tempo.cat <- paste0("\n\n================\n\nERROR IN fun_refactorization(): REQUIRED fun_param_check() FUNCTION IS MISSING IN THE R ENVIRONMENT\n\n================\n\n")
        stop(tempo.cat)
    }
    # end required function checking
    # argument checking
    arg.check <- NULL # for function debbuging
    checked.arg.names <- NULL # for function debbuging
    ee <- expression(arg.check <- c(arg.check, tempo$problem) , checked.arg.names <- c(checked.arg.names, tempo$param.name))
    tempo <- fun_param_check(data = also.ordered, class = "logical", length = 1) ; eval(ee)
    if(any(arg.check) == TRUE){
        stop() # nothing else because print = TRUE by default in fun_param_check()
    }
    # source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.2/r_debugging_tools-v1.2.R") ; eval(parse(text = str_basic_arg_check_dev)) ; eval(parse(text = str_arg_check_with_fun_param_check_dev)) # activate this line and use the function to check arguments status and if they have been checked using fun_param_check()
    if(also.ordered == FALSE){
        if( ! (all(class(data) == "data.frame") | all(class(data) == "factor"))){
            tempo.cat <- paste0("\n\n================\n\nERROR IN fun_refactorization(): 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 IN fun_refactorization(): 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)
        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)
        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])
            }
        }
        tempo.ordered.col <- sapply(sapply(lapply(data, class), FUN = "%in%", "ordered"), FUN = "any") # get the ordered factor column (logical) if they exist
        if(also.ordered == TRUE){
            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])
                }
            }
        }
        text <- text[(tempo.factor.col | tempo.ordered.col) & ! (sapply(text, FUN = length) == 0)] # remove the compartments of text that are not modified factors columns of data frame
    }
    output <- list(data = data, removed = text)
    return(output)
Gael  MILLOT's avatar
Gael MILLOT committed
1216
1217
1218
1219
1220
1221
1222
1223
}


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


# Check OK: clear to go Apollo
fun_rounding <- function(data, dec.nb = 2, after.lead.zero = TRUE){
Gael  MILLOT's avatar
Gael MILLOT committed
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
    # AIM:
    # round a vector of values, 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
    # cat(fun_rounding(data = c(10, 100.001, 333.0001254, 12312.1235), dec.nb = 2, after.lead.zero = FALSE))
    # cat(fun_rounding(data = c("10", "100.001", "333.0001254", "12312.1235"), dec.nb = 2, after.lead.zero = FALSE))
    # DEBUGGING
    # data = data = c(10, 100.001, 333.0001254, 12312.1235) ; dec.nb = 2 ; after.lead.zero = FALSE # # for function debugging
    # data = data = c("10", "100.001", "333.0001254", "12312.1235") ; dec.nb = 2 ; after.lead.zero = TRUE # # for function debugging
    # argument checking
    if( ! (all(typeof(data) == "character") | all(typeof(data) == "double") | all(typeof(data) == "integer"))){
        tempo.cat <- paste0("\n\n================\n\nERROR IN fun_rounding(): 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
    checked.arg.names <- NULL # for function debbuging
    ee <- expression(arg.check <- c(arg.check, tempo$problem) , checked.arg.names <- c(checked.arg.names, tempo$param.name))
    tempo <- fun_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() # nothing else because print = TRUE by default in fun_param_check()
    }
    # source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.2/r_debugging_tools-v1.2.R") ; eval(parse(text = str_basic_arg_check_dev)) ; eval(parse(text = str_arg_check_with_fun_param_check_dev)) # activate this line and use the function to check arguments status and if they have been checked using fun_param_check()
    # 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
Gael  MILLOT's avatar
Gael MILLOT committed
1286
1287
1288
1289


# Check OK: clear to go Apollo
fun_90clock_matrix_rot <- function(data){
Gael  MILLOT's avatar
Gael MILLOT committed
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
    # 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
    # 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)
    # DEBUGGING
    # data = matrix(1:10, ncol = 1)
    # required function checking
    if(length(find("fun_param_check", mode = "function")) == 0){
        tempo.cat <- paste0("\n\n================\n\nERROR IN fun_90clock_matrix_rot(): REQUIRED fun_param_check() FUNCTION IS MISSING IN THE R ENVIRONMENT\n\n================\n\n")
        stop(tempo.cat)
    }
    # end required function checking
    # argument checking
    # source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.2/r_debugging_tools-v1.2.R") ; eval(parse(text = str_basic_arg_check_dev)) # activate this line and use the function to check arguments status and if they have been checked using fun_param_check()
    if( ! any(class(data) %in% "matrix")){
        tempo.cat <- paste0("\n\n================\n\nERROR IN fun_90clock_matrix_rot(): THE data ARGUMENT MUST BE A MATRIX\n\n================\n\n")
        stop(tempo.cat)
    }
    # end argument checking
    for (i in 1:ncol(data)){data[,i] <- rev(data[,i])}
    data <- t(data)
    return(data)
Gael  MILLOT's avatar
Gael MILLOT committed
1320
1321
1322
1323
1324
1325
1326
1327
}


######## 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){
Gael  MILLOT's avatar
Gael MILLOT committed
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
    # AIM:
    # convert a matrix made of numbers 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
    # EXAMPLES
    # 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)
    # DEBUGGING
    # mat1 = matrix(c(1,1,1,2,1,5,9,NA), ncol = 2) ; dimnames(mat1) <- list(LETTERS[1:4], letters[1:2]); mat.hsv.h = FALSE ; notch = 1 ; s = 1 ; v = 1 ; forced.color = c(hsv(1,1,1), hsv(0,0,0)) # for function debugging
    # required function checking
    if(length(find("fun_param_check", mode = "function")) == 0){
        tempo.cat <- paste0("\n\n================\n\nERROR IN fun_hexa_hsv_color_matrix(): REQUIRED fun_param_check() FUNCTION IS MISSING IN THE R ENVIRONMENT\n\n================\n\n")
        stop(tempo.cat)
    }
    # end required function checking
    # argument checking
    arg.check <- NULL # for function debbuging
    checked.arg.names <- NULL # for function debbuging
    ee <- expression(arg.check <- c(arg.check, tempo$problem) , checked.arg.names <- c(checked.arg.names, tempo$param.name))
    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() # nothing else because print = TRUE by default in fun_param_check()
    }
    # source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.2/r_debugging_tools-v1.2.R") ; eval(parse(text = str_basic_arg_check_dev)) ; eval(parse(text = str_arg_check_with_fun_param_check_dev)) # activate this line and use the function to check arguments status and if they have been checked using fun_param_check()
    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 IN fun_hexa_hsv_color_matrix(): 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 IN fun_hexa_hsv_color_matrix(): 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 IN fun_hexa_hsv_color_matrix(): mat1 MUST BE MADE OF VALUES BETWEEN 0 AND 1 BECAUSE mat.hsv.h ARGUMENT SET TO TRUE\n\n================\n\n")
            stop(tempo.cat)
        }
    }else{
        if(any(mat1 - floor(mat1) > 0, na.rm = TRUE) | any(mat1 == 0, na.rm = TRUE)){
            tempo.cat <- paste0("\n\n================\n\nERROR IN fun_hexa_hsv_color_matrix(): mat1 MUST BE MADE OF INTEGER VALUES WITHOUT 0 BECAUSE mat.hsv.h ARGUMENT SET TO FALSE\n\n================\n\n")
            stop(tempo.cat)
        }else{
            mat1 <- mat1 / max(mat1, na.rm = TRUE)
        }
    }
    if(notch != 1){
        different.color <- unique(as.vector(mat1))
        different.color <- different.color[ ! is.na(different.color)]
        tempo.different.color <- different.color + c(0, cumsum(rep(notch, length(different.color) - 1)))
        tempo.different.color <- tempo.different.color - floor(tempo.different.color)
        if(any(duplicated(tempo.different.color) == TRUE)){
            tempo.cat <- paste0("\n\n================\n\nERROR IN fun_hexa_hsv_color_matrix(): DUPLICATED VALUES AFTER USING notch (", paste(tempo.different.color[duplicated(tempo.different.color)], collapse = " "), "). TRY ANOTHER notch VALUE\n\n================\n\n")
            stop(tempo.cat)
        }else if(length(different.color) != length(tempo.different.color)){
            tempo.cat <- paste0("\n\n================\n\nERROR IN fun_hexa_hsv_color_matrix(): LENGTH OF different.color (", paste(different.color, collapse = " "), ") DIFFERENT FROM LENGTH OF tempo.different.color (", paste(tempo.different.color, collapse = " "), ")\n\n================\n\n")
            stop(tempo.cat)
        }else{
            for(i in 1:length(different.color)){
                mat1[mat1 == different.color[i]] <- tempo.different.color[i]
            }
        }
    }
    if( ! is.null(forced.color)){
        hexa.values.to.change <- hsv(unique(sort(mat1))[1:length(forced.color)], s, v)
    }
    mat1[ ! is.na(mat1)] <- hsv(mat1[ ! is.na(mat1)], s, v)
    if( ! is.null(forced.color)){
        if(any(forced.color %in% mat1, na.rm = TRUE)){
            problem <- TRUE
            text.problem <- paste0("THE FOLLOWING COLORS WHERE INTRODUCED USING forced.color BUT WHERE ALREADY PRESENT IN THE COLORED MATRIX :", paste(forced.color[forced.color %in% mat1], collapse = " "))
        }else{
            problem <- FALSE
        }
        for(i in 1:length(hexa.values.to.change)){
            if( ! any(mat1 == hexa.values.to.change[i], na.rm = TRUE)){
                tempo.cat <- paste0("\n\n================\n\nERROR IN fun_hexa_hsv_color_matrix(): 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)
}


######## fun_by_case_matrix_op() #### assembling of several matrices with operation


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


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
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
######## fun_mat_inv() #### return the inverse of a square matrix


# Check OK: clear to go Apollo
fun_mat_inv <- function(mat){
    # AIM:
    # return the inverse of a square matrix when solve() cannot
    # REQUIRED FUNCTIONS
    # fun_param_check()
    # ARGUMENTS:
    # mat: a square numeric matrix without NULL, NA, Inf or single case (dimension 1, 1) of 0
    # RETURN
    # the inversed matrix
    # EXAMPLES
    # mat1 = matrix(c(1,1,1,2,1,5,9,8,9), ncol = 3) ; fun_mat_inv(mat = mat1) # use solve()
    # mat1 = matrix(c(0,0,0,0,0,0,0,0,0), ncol = 3) ; fun_mat_inv(mat = mat1) # use the trick
    # mat1 = matrix(c(1,1,1,2,Inf,5,9,8,9), ncol = 3) ; fun_mat_inv(mat = mat1)
    # mat1 = matrix(c(1,1,1,2,NA,5,9,8,9), ncol = 3) ; fun_mat_inv(mat = mat1)
    # mat1 = matrix(c(1,2), ncol = 1) ; fun_mat_inv(mat = mat1)
    # mat1 = matrix(0, ncol = 1) ; fun_mat_inv(mat = mat1)
    # mat1 = matrix(2, ncol = 1) ; fun_mat_inv(mat = mat1)
    # DEBUGGING
    # mat = matrix(c(1,1,1,2,1,5,9,8,9), ncol = 3) # for function debugging
    # required function checking
    if(length(find("fun_param_check", mode = "function")) == 0){
        tempo.cat <- paste0("\n\n================\n\nERROR IN fun_mat_inv(): REQUIRED fun_param_check() FUNCTION IS MISSING IN THE R ENVIRONMENT\n\n================\n\n")
        stop(tempo.cat)
    }
    # end required function checking
    # argument checking
    arg.check <- NULL # for function debbuging
    checked.arg.names <- NULL # for function debbuging
    ee <- expression(arg.check <- c(arg.check, tempo$problem) , checked.arg.names <- c(checked.arg.names, tempo$param.name))
    tempo <- fun_param_check(data = mat, class = "matrix", mode = "numeric") ; eval(ee)
    if(any(arg.check) == TRUE){
        stop() # nothing else because print = TRUE by default in fun_param_check()
    }
    # source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.2/r_debugging_tools-v1.2.R") ; eval(parse(text = str_basic_arg_check_dev)) ; eval(parse(text = str_arg_check_with_fun_param_check_dev)) # activate this line and use the function to check arguments status and if they have been checked using fun_param_check()
    if(ncol(mat) != nrow(mat)){
        tempo.cat <- paste0("\n\n================\n\nERROR IN fun_mat_inv(): mat ARGUMENT MUST BE A SQUARE MATRIX\n\n================\n\n")
        stop(tempo.cat)
    }
    if(any(mat %in% c(Inf, -Inf, NA))){
        tempo.cat <- paste0("\n\n================\n\nERROR IN fun_mat_inv(): mat ARGUMENT MUST BE A MATRIX WITHOUT Inf, -Inf OR NA\n\n================\n\n")
        stop(tempo.cat)
    }
    if(all(mat == 0) & ncol(mat) == 1){
        tempo.cat <- paste0("\n\n================\n\nERROR IN fun_mat_inv(): mat ARGUMENT CANNOT BE A SQUARE MATRIX MADE OF A SINGLE CASE OF 0\n\n================\n\n")
        stop(tempo.cat)
    }
    # end argument checking
    if(any(grepl(x = try(solve(mat), silent = TRUE)[], pattern = "Error"))){
        tempo <- svd(mat)
        val.critique <- which(tempo$d < 10^-8)
        Diag.mod <- diag(1 / tempo$d)
        for(i in val.critique){
            Diag.mod[i, i] <- 0
        }
        return(tempo$v %*% Diag.mod %*% t(tempo$u))
    }else{
        return(solve(mat))
    }
}


Gael  MILLOT's avatar
Gael MILLOT committed
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
################ 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){
Gael  MILLOT's avatar
Gael MILLOT committed
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
    # 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)
    # DEBUGGING
    # class.nb = 10 ; inches.per.class.nb = 0.2 ; ini.window.width = 7 ; inch.left.space = 1 ; inch.right.space = 1 ; boundarie.space = 0.5 # for function debugging
    # required function checking
    if(length(find("fun_param_check", mode = "function")) == 0){
        tempo.cat <- paste0("\n\n================\n\nERROR IN fun_window_width_resizing(): REQUIRED fun_param_check() FUNCTION IS MISSING IN THE R ENVIRONMENT\n\n================\n\n")
        stop(tempo.cat)
    }
    # end required function checking
    # argument checking
    arg.check <- NULL # for function debbuging
    checked.arg.names <- NULL # for function debbuging
    ee <- expression(arg.check <- c(arg.check, tempo$problem) , checked.arg.names <- c(checked.arg.names, tempo$param.name))
    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() # nothing else because print = TRUE by default in fun_param_check()
    }
    # source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.2/r_debugging_tools-v1.2.R") ; eval(parse(text = str_basic_arg_check_dev)) ; eval(parse(text = str_arg_check_with_fun_param_check_dev)) # activate this line and use the function to check arguments status and if they have been checked using fun_param_check()
    # 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)
Gael  MILLOT's avatar
Gael MILLOT committed
1669
1670
1671
1672
1673
1674
1675
1676
}


######## 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){
Gael  MILLOT's avatar
Gael MILLOT committed
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
    # 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. Write "working.dir" if working directory is required (default)
    # pdf.name.file: name of the pdf file containing the graphs (the .pdf extension is added by the function)
    # width.fun: width of the windows (in inches)
    # height.fun: height of the windows (in inches)
    # paper: paper argument of the pdf function (paper format). Only used for pdf(). Either "a4", "letter", "legal", "us", "executive", "a4r", "USr" or "special". If "special", means that width.fun and height.fun specify the paper size
    # no.pdf.overwrite: existing pdf can be overwritten ? Only used if pdf.disp = TRUE
    # return.output: return output ? If TRUE but function not assigned, the output list is displayed
    # RETURN
    # a list containing:
    # $pdf.loc: path of the pdf created
    # $ini.par: initial par() parameters (to reset in a new graph)
    # $zone.ini: initial window spliting (to reset in a new graph)
    # EXAMPLES
    # fun_open_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)
    # DEBUGGING
    # pdf.disp = TRUE ; path.fun = "C:/Users/Gael/Desktop" ; pdf.name.file = "graphs" ; width.fun = 7 ; height.fun = 7 ; paper = "special" ; no.pdf.overwrite = TRUE ; return.output = TRUE # for function debugging
    # pdf.disp = TRUE ; path.fun = "/pasteur/homes/gmillot/" ; pdf.name.file = "graphs" ; width.fun = 7 ; height.fun = 7 ; paper = "special" ; no.pdf.overwrite = TRUE ; return.output = TRUE # for function debugging
    # required function checking
    if(length(find("fun_param_check", mode = "function")) == 0){
        tempo.cat <- paste0("\n\n================\n\nERROR IN fun_open_window(): REQUIRED fun_param_check() FUNCTION IS MISSING IN THE R ENVIRONMENT\n\n================\n\n")
        stop(tempo.cat)
    }
    # end required function checking
    # argument checking
    arg.check <- NULL # for function debbuging
    checked.arg.names <- NULL # for function debbuging
    ee <- expression(arg.check <- c(arg.check, tempo$problem) , checked.arg.names <- c(checked.arg.names, tempo$param.name))
    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() # nothing else because print = TRUE by default in fun_param_check()
    }
    # source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.2/r_debugging_tools-v1.2.R") ; eval(parse(text = str_basic_arg_check_dev)) ; eval(parse(text = str_arg_check_with_fun_param_check_dev)) # activate this line and use the function to check arguments status and if they have been checked using fun_param_check()
    # end argument checking
    if(path.fun == "working.dir"){
        path.fun <- getwd()
    }else{
        if(grepl(x = path.fun, pattern = ".+/$")){
            path.fun <- substr(path.fun, 1, nchar(path.fun) - 1) # remove the last /
        }
        if(dir.exists(path.fun) == FALSE){
            tempo.cat <- paste0("\n\n================\n\nERROR IN fun_open_window(): path.fun ARGUMENT DOES NOT CORRESPOND TO EXISTING DIRECTORY\n\n================\n\n")
            stop(tempo.cat)
        }
    }
    if(Sys.info()["sysname"] == "Windows"){ # Note that .Platform$OS.type() only says "unix" for macOS and Linux and "Windows" for Windows
        open.fail <- NULL
        windows()
        ini.par <- par(no.readonly = TRUE) # to recover the initial graphical parameters if required (reset). BEWARE: this command alone opens a pdf of GUI window if no window already opened. But here, protected with the code bacause always a tempo window opened
        invisible(dev.off()) # close the new window
    }else if(Sys.info()["sysname"] == "Linux"){
        if(pdf.disp == TRUE){
            if(file.exists(paste0(path.fun, "/recover_ini_par.pdf"))){
                tempo.cat <- paste0("\n\n================\n\nPROBLEM IN fun_open_window(): THIS FUNCTION CANNOT BE USED ON LINUX IF A recover_ini_par.pdf FILE ALREADY EXISTS HERE: ", paste(path.fun, collapse = " "), "\n\n================\n\n")
                stop(tempo.cat)
            }else{
                pdf(width = width.fun, height = height.fun, file=paste0(path.fun, "/recover_ini_par.pdf"), paper = paper)
                ini.par <- par(no.readonly = TRUE) # to recover the initial graphical parameters if required (reset). BEWARE: this command alone opens a pdf of GUI window if no window already opened. But here, protected with the code bacause always a tempo window opened
                invisible(dev.off()) # close the pdf windows
                file.remove(paste0(path.fun, "/recover_ini_par.pdf")) # remove the pdf file
            }
        }else{
            # test if X11 can be opened
            if(file.exists(paste0(getwd(), "/Rplots.pdf"))){
                tempo.cat <- paste0("\n\n================\n\nERROR IN fun_open_window(): THIS FUNCTION CANNOT BE USED ON LINUX IF A Rplots.pdf FILE ALREADY EXISTS HERE: ", getwd(), "\n\n================\n\n")
                stop(tempo.cat)
            }else{
                open.fail <- suppressWarnings(try(X11(), silent = TRUE))[] # try to open a X11 window. If open.fail == NULL, no problem, meaning that the X11 window is opened. If open.fail != NULL, a pdf can be opened here paste0(getwd(), "/Rplots.pdf")
                if(is.null(open.fail)){
                    ini.par <- par(no.readonly = TRUE) # to recover the initial graphical parameters if required (reset). BEWARE: this command alone opens a pdf of GUI window if no window already opened. But here, protected with the code bacause always a tempo window opened
                    invisible(dev.off()) # close the new window
                }else if(file.exists(paste0(getwd(), "/Rplots.pdf"))){
                    file.remove(paste0(getwd(), "/Rplots.pdf")) # remove the pdf file
                    tempo.cat <- ("\n\n================\n\nPROBLEM IN fun_open_window(): THIS FUNCTION CANNOT OPEN GUI ON LINUX OR NON MACOS UNIX SYSTEM (X GRAPHIC INTERFACE HAS TO BE SET).\nTO OVERCOME THIS, PLEASE SET pdf.disp ARGUMENT TO TRUE AND RERUN\n\n================\n\n")
                    stop(tempo.cat)
                }
            }
        }
    }else{
        open.fail <- NULL
        quartz()
        ini.par <- par(no.readonly = TRUE) # to recover the initial graphical parameters if required (reset). BEWARE: this command alone opens a pdf of GUI window if no window already opened. But here, protected with the code bacause always a tempo window opened
        invisible(dev.off()) # close the new window
    }
    zone.ini <- matrix(1, ncol=1) # to recover the initial parameters for next figure region when device region split into several figure regions
    if(pdf.disp == TRUE){
        pdf.loc <- paste0(path.fun, "/", pdf.name.file, ".pdf")
        if(file.exists(pdf.loc) == TRUE & no.pdf.overwrite == TRUE){
            tempo.cat <- paste0("\n\n================\n\nERROR IN fun_open_window(): pdf.loc FILE ALREADY EXISTS AND CANNOT BE OVERWRITTEN DUE TO no.pdf.overwrite ARGUMENT SET TO TRUE: ", pdf.loc, "\n\n================\n\n")
            stop(tempo.cat)
        }else{
            pdf(width = width.fun, height = height.fun, file=pdf.loc, paper = paper)
        }
    }else if(pdf.disp == FALSE){
        pdf.loc <- NULL
        if(Sys.info()["sysname"] == "Windows"){ # .Platform$OS.type() only says "unix" for macOS and Linux and "Windows" for Windows
            windows(width = width.fun, height = height.fun, rescale="fixed")
        }else if(Sys.info()["sysname"] == "Linux"){
            if( ! is.null(open.fail)){
                stop("\n\n================\n\nPROBLEM IN fun_open_window(): THIS FUNCTION CANNOT OPEN GUI ON LINUX OR NON MACOS UNIX SYSTEM (X GRAPHIC INTERFACE HAS TO BE SET).\nTO OVERCOME THIS, PLEASE SET pdf.disp ARGUMENT TO TRUE AND RERUN\n\n================\n\n")
            }else{
                X11(width = width.fun, height = height.fun)
            }
        }else{
            quartz(width = width.fun, height = height.fun)
        }
    }
    if(return.output == TRUE){
        output <- list(pdf.loc = pdf.loc, ini.par = ini.par, zone.ini = zone.ini)
        return(output)
    }
Gael  MILLOT's avatar
Gael MILLOT committed
1809
1810
1811
1812
1813
1814
1815
1816
}


######## 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){
Gael  MILLOT's avatar
Gael MILLOT committed
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
    # AIM:
    # very convenient to erase the axes for post plot axis redrawing using fun_feature_post_plot()
    # reinitialize and set the graphic parameters before plotting
    # CANNOT be used if no graphic device already opened
    # 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, std.x.range = TRUE, std.y.range = TRUE, down.space = 1, left.space = 1, up.space = 1, right.space = 1, orient = 1, dist.legend = 4.5, tick.length = 0.5, box.type = "n", amplif.label = 1, amplif.axis = 1, display.extend = FALSE, return.par = FALSE)
    # DEBUGGING
    # param.reinitial = FALSE ; xlog.scale = FALSE ; ylog.scale = FALSE ; remove.label = TRUE ; remove.x.axis = TRUE ; remove.y.axis = TRUE ; std.x.range = TRUE ; std.y.range = TRUE ; down.space = 1 ; left.space = 1 ; up.space = 1 ; right.space = 1 ; orient = 1 ; dist.legend = 4.5 ; tick.length = 0.5 ; box.type = "n" ; amplif.label = 1 ; amplif.axis = 1 ; display.extend = FALSE ; return.par = FALSE # for function debugging
    # required function checking
    if(length(find("fun_param_check", mode = "function")) == 0){
        tempo.cat <- paste0("\n\n================\n\nERROR IN fun_graph_param_prior_plot(): REQUIRED fun_param_check() FUNCTION IS MISSING IN THE R ENVIRONMENT\n\n================\n\n")
        stop(tempo.cat)
    }
    # end required function checking
    # argument checking
    arg.check <- NULL # for function debbuging
    checked.arg.names <- NULL # for function debbuging
    ee <- expression(arg.check <- c(arg.check, tempo$problem) , checked.arg.names <- c(checked.arg.names, tempo$param.name))
    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)
Gael  MILLOT's avatar
Gael MILLOT committed
1868
1869
1870
1871
1872
1873
1874
    tempo <- fun_param_check(data = down.space, mode = "numeric", length = 1, neg.values = FALSE) ; eval(ee)
    tempo <- fun_param_check(data = left.space, mode = "numeric", length = 1, neg.values = FALSE) ; eval(ee)
    tempo <- fun_param_check(data = up.space, mode = "numeric", length = 1, neg.values = FALSE) ; eval(ee)
    tempo <- fun_param_check(data = right.space, mode = "numeric", length = 1, neg.values = FALSE) ; eval(ee)
    tempo <- fun_param_check(data = orient, mode = "numeric", length = 1, neg.values = FALSE) ; eval(ee)
    tempo <- fun_param_check(data = dist.legend, mode = "numeric", length = 1, neg.values = FALSE) ; eval(ee)
    tempo <- fun_param_check(data = tick.length, mode = "numeric", length = 1, prop = TRUE) ; eval(ee)
Gael  MILLOT's avatar
Gael MILLOT committed
1875
    tempo <- fun_param_check(data = box.type, options = c("o", "l", "7", "c", "u", "]", "n"), length = 1) ; eval(ee)
Gael  MILLOT's avatar
Gael MILLOT committed
1876
1877
    tempo <- fun_param_check(data = amplif.label, mode = "numeric", length = 1, neg.values = FALSE) ; eval(ee)
    tempo <- fun_param_check(data = amplif.axis, mode = "numeric", length = 1, neg.values = FALSE) ; eval(ee)
Gael  MILLOT's avatar
Gael MILLOT committed
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
    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() # nothing else because print = TRUE by default in fun_param_check()
    }
    # source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.2/r_debugging_tools-v1.2.R") ; eval(parse(text = str_basic_arg_check_dev)) ; eval(parse(text = str_arg_check_with_fun_param_check_dev)) # activate this line and use the function to check arguments status and if they have been checked using fun_param_check()
    # end argument checking
    if(is.null(dev.list())){
        tempo.cat <- paste0("\n\n================\n\nERROR IN fun_graph_param_prior_plot(): THIS FUNCTION CANNOT BE USED IF NO GRAPHIC DEVICE ALREADY OPENED (dev.list() IS CURRENTLY NULL)\n\n================\n\n")
        stop(tempo.cat)
    }
    if(param.reinitial == TRUE){
        if( ! all(names(dev.cur()) == "null device")){
            active.wind.nb <- dev.cur()
        }else{
            active.wind.nb <- 0
        }
        if(Sys.info()["sysname"] == "Windows"){ # Note that .Platform$OS.type() only says "unix" for macOS and Linux and "Windows" for Windows
            windows()
            ini.par <- par(no.readonly = TRUE)  # to recover the initial graphical parameters if required (reset). BEWARE: this command alone opens a pdf of GUI window if no window already opened. But here, protected with the code bacause always a tempo window opened
            invisible(dev.off()) # close the new window
        }else if(Sys.info()["sysname"] == "Linux"){
            if(file.exists(paste0(getwd(), "/Rplots.pdf"))){
                tempo.cat <- paste0("\n\n================\n\nERROR IN fun_graph_param_prior_plot(): THIS FUNCTION CANNOT BE USED ON LINUX WITH param.reinitial SET TO TRUE IF A Rplots.pdf FILE ALREADY EXISTS HERE: ", getwd(), "\n\n================\n\n")
                stop(tempo.cat)
            }else{
                open.fail <- suppressWarnings(try(X11(), silent = TRUE))[] # try to open a X11 window. If open.fail == NULL, no problem, meaning that the X11 window is opened. If open.fail != NULL, a pdf can be opened here paste0(getwd(), "/Rplots.pdf")
                if(is.null(open.fail)){
                    ini.par <- par(no.readonly = TRUE) # to recover the initial graphical parameters if required (reset). BEWARE: this command alone opens a pdf of GUI window if no window already opened. But here, protected with the code bacause always a tempo window opened
                    invisible(dev.off()) # close the new window
                }else if(file.exists(paste0(getwd(), "/Rplots.pdf"))){
                    ini.par <- par(no.readonly = TRUE) # to recover the initial graphical parameters if required (reset). BEWARE: this command alone opens a pdf of GUI window if no window already opened. But here, protected with the code bacause always a tempo window opened
                    invisible(dev.off()) # close the new window
                    file.remove(paste0(getwd(), "/Rplots.pdf")) # remove the pdf file
                }else{
                    tempo.cat <- ("\n\n================\n\nPROBLEM IN fun_graph_param_prior_plot(): THIS FUNCTION CANNOT OPEN GUI ON LINUX OR NON MACOS UNIX SYSTEM (X GRAPHIC INTERFACE HAS TO BE SET).\nTO OVERCOME THIS, PLEASE USE PDF GRAPHIC INTERFACES AND RERUN\n\n================\n\n")
                    stop(tempo.cat)
                }
            }
        }else{ # macOS
            quartz()
            ini.par <- par(no.readonly = TRUE)  # to recover the initial graphical parameters if required (reset). BEWARE: this command alone opens a pdf of GUI window if no window already opened. But here, protected with the code bacause always a tempo window opened)
            invisible(dev.off()) # close the new window
        }
        if( ! all(names(dev.cur()) == "null device")){
            dev.set(active.wind.nb) # go back to the active windows if exists
            par(ini.par) # apply the initial par to current window
        }
    }
    if(remove.x.axis == TRUE){
        par(xaxt = "n") # suppress the y-axis label
    }else{
        par(xaxt = "s")
    }
    if(remove.y.axis == TRUE){
        par(yaxt = "n") # suppress the y-axis label
    }else{
        par(yaxt = "s")
    }
    if(std.x.range == TRUE){
        par(xaxs = "i")
    }else{
        par(xaxs = "r")
    }
    if(std.y.range == TRUE){
        par(yaxs = "i")
    }else{
        par(yaxs = "r")
    }
    par(mai = c(down.space, left.space, up.space, right.space), ann = ! remove.label, las = orient, mgp = c(dist.legend/0.2, 1, 0), xpd = display.extend, bty= box.type, cex.lab = amplif.label, cex.axis = amplif.axis)
    par(tcl = -par()$mgp[2] * tick.length) # tcl gives the length of the ticks as proportion of line text, knowing that mgp is in text lines. So the main ticks are a 0.5 of the distance of the axis numbers by default. The sign provides the side of the tick (negative for outside of the plot region)
    if(xlog.scale == TRUE){
        par(xaxt = "n", xlog = TRUE) # suppress the x-axis label
    }else{
        par(xlog = FALSE)
    }
    if(ylog.scale == TRUE){
        par(yaxt = "n", ylog = TRUE) # suppress the y-axis label
    }else{
        par(ylog = FALSE)
    }
    if(return.par == TRUE){
        tempo.par <- par()
        return(tempo.par)
    }
Gael  MILLOT's avatar
Gael MILLOT committed
1963
1964
1965
1966
1967
1968
1969
}


######## fun_feature_post_plot() #### Graph param after plotting


# Check OK: clear to go Apollo
Gael  MILLOT's avatar
Gael MILLOT committed
1970
fun_feature_post_plot <- function(x.side = 0, x.log.scale = FALSE, x.categ = NULL, x.categ.pos = NULL, x.lab = "", x.axis.magnific = 1.5, x.label.magnific = 1.5, x.dist.legend = 0.5, x.nb.inter.tick = 1, y.side = 0, y.log.scale = FALSE, y.categ = NULL, y.categ.pos = NULL, y.lab = "", y.axis.magnific = 1.5, y.label.magnific = 1.5, y.dist.legend = 0.5, y.nb.inter.tick = 1, text.angle = 90, tick.length = 0.5, sec.tick.length = 0.3, bg.color = NULL, grid.lwd = NULL, grid.col = "white", corner.text = "", magnific.corner.text = 1, just.label.add = FALSE, par.reset = FALSE, custom.par = NULL){
Gael  MILLOT's avatar
Gael MILLOT committed
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
    # AIM:
    # redesign axis. If x.side = 0, y.side = 0, the function just adds text at topright of the graph and reset par() for next graphics and provides outputs (see below)
    # provide also positions for legend or additional text on the graph
    # use fun_graph_param_prior_plot() before this function for initial inactivation of the axis drawings
    # REQUIRED FUNCTIONS
    # fun_param_check()
    # fun_open_window() to reinitialize graph parameters if par.reset = TRUE and custom.par = NULL
    # ARGUMENTS
    # x.side: axis at the bottom (1) or top (3) of the region figure. Write 0 for no change
    # x.log.scale: Log scale for the x-axis? Either TRUE or FALSE
    # x.categ: character vector representing the classes (levels()) to specify when the x-axis is qualititative(stripchart, boxplot)
    # x.categ.pos: position of the classes names (numeric vector of identical length than x.categ). If left NULL, this will be 1:length(levels())
    # x.lab: label of the x-axis. If x.side == 0 and x.lab != "", then x.lab is printed
    # x.axis.magnific: increase or decrease the value to increase or decrease the size of the x axis numbers. Also control the size of displayed categories
    # x.label.magnific: increase or decrease the value to increase or decrease the size of the x axis legend
    # x.dist.legend: increase the number to move x-axis legends away in inches (first number of mgp argument of par() but in inches)
    # x.nb.inter.tick: number of secondary ticks between main ticks on x-axis (only if not log scale). 0 means no secondary ticks
    # y.side: axis at the left (2) or right (4) of the region figure. Write 0 for no change
    # y.log.scale: Log scale for the y-axis? Either TRUE or FALSE
    # y.categ: classes (levels()) to specify when the y-axis is qualititative(stripchart, boxplot)
    # y.categ.pos: position of the classes names (numeric vector of identical length than y.categ). If left NULL, this will be 1:length(levels())
    # y.lab: label of the y-axis. If y.side == 0 and y.lab != "", then y.lab is printed
    # y.axis.magnific: increase or decrease the value to increase or decrease the size of the y axis numbers. Also control the size of displayed categories
    # y.label.magnific: increase or decrease the value to increase or decrease the size of the y axis legend
    # y.dist.legend: increase the number to move y-axis legends away in inches (first number of mgp argument of par() but in inches)
    # y.nb.inter.tick: number of secondary ticks between main ticks on y-axis (only if not log scale). 0 means non secondary ticks
    # text.angle: angle of the text when axis is qualitative
    # tick.length: length of the main ticks (1 means complete the distance between the plot region and the axis numbers, 0.5 means half the length, etc., 0 for no ticks)
    # sec.tick.length: length of the secondary ticks (1 means complete the distance between the plot region and the axis numbers, 0.5 means half the length, etc., 0 for no ticks)
    # bg.color: background color of the plot region. NULL for no color. BEWARE: cover/hide an existing plot !