cute_little_R_functions.R 895 KB
Newer Older
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
text.check <- c(text.check, tempo.cat)
arg.check <- c(arg.check, TRUE)
}
}
}
if( ! is.null(lib.path)){
tempo <- fun_check(data = lib.path, class = "vector", mode = "character", fun.name = function.name) ; eval(ee)
if(tempo$problem == FALSE){
if( ! all(dir.exists(lib.path))){ # separation to avoid the problem of tempo$problem == FALSE and lib.path == NA
tempo.cat <- paste0("ERROR IN ", function.name, ": DIRECTORY PATH INDICATED IN THE lib.path ARGUMENT DOES NOT EXISTS:\n", paste(lib.path, collapse = "\n"))
text.check <- c(text.check, tempo.cat)
arg.check <- c(arg.check, TRUE)
}
}
}
if( ! is.null(thread.nb)){
tempo <- fun_check(data = cute.path, class = "vector", typeof = "character", length = 1, fun.name = function.name) ; eval(ee)
if(tempo$problem == FALSE){
if( ! file.exists(cute.path)){
tempo.cat <- paste0("ERROR IN ", function.name, ": FILE PATH INDICATED IN THE cute.path PARAMETER DOES NOT EXISTS:\n", cute.path)
text.check <- c(text.check, tempo.cat)
arg.check <- c(arg.check, TRUE)
}
}
}
if(any(arg.check) == TRUE){
stop(paste0("\n\n================\n\n", paste(text.check[arg.check], collapse = "\n"), "\n\n================\n\n"), call. = FALSE) #
}
# end using fun_check()
Gael's avatar
tempo    
Gael committed
2030
# source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.7/r_debugging_tools-v1.7.R") ; eval(parse(text = str_basic_arg_check_dev)) ; eval(parse(text = str_arg_check_with_fun_check_dev)) # activate this line and use the function (with no arguments left as NULL) to check arguments status and if they have been checked using fun_check()
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
# end argument primary checking
# second round of checking and data preparation
# management of NA
if(any(is.na(fun)) | any(is.na(arg)) | any(is.na(expect.error)) | any(is.na(thread.nb)) | any(is.na(print.count)) | any(is.na(plot.fun)) | any(is.na(export)) | any(is.na(res.path)) | any(is.na(lib.path))){
tempo.cat <- paste0("ERROR IN ", function.name, ": NO ARGUMENT EXCEPT val CAN HAVE NA VALUES")
stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
}
# end management of NA
# management of NULL
if(is.null(fun) | is.null(arg) | is.null(val) | is.null(print.count) | is.null(plot.fun) | is.null(export)){
tempo.cat <- paste0("ERROR IN ", function.name, ": THESE ARGUMENTS\nfun\narg\nval\nprint.count\nplot.fun\nexport\nCANNOT BE NULL") #problematic arguments are -> put everywhere
stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
}
# end management of NULL
2045
2046
if(base::length(arg) != base::length(val)){
tempo.cat <- paste0("ERROR IN ", function.name, ": LENGTH OF arg ARGUMENT MUST BE IDENTICAL TO LENGTH OF val ARGUMENT:\nHERE IT IS: ", base::length(arg), " VERSUS ", base::length(val))
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE)
}
args <- names(formals(get(fun))) # here no env = sys.nframe(), inherit = FALSE for get() because fun is a function in the classical scope
if( ! all(arg %in% args)){
tempo.cat <- paste0("ERROR IN ", function.name, ": SOME OF THE STRINGS IN arg ARE NOT ARGUMENTS OF fun\nfun ARGUMENTS: ", paste(args, collapse = " "),"\nPROBLEMATIC STRINGS IN arg: ", paste(arg[ ! arg %in% args], collapse = " "))
stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE)
}
if(sum(sapply(val, FUN = length) > 1) > 43){
tempo.cat <- paste0("ERROR IN ", function.name, ": CANNOT TEST MORE THAN 43 ARGUMENTS IF THEY ALL HAVE AT LEAST 2 VALUES EACH\nHERE THE NUMBER IS: ", sum(sapply(val, FUN = length) > 1))
stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE)
}
if( ! is.null(expect.error)){
2059
2060
if(base::length(val) != base::length(expect.error)){
tempo.cat <- paste0("ERROR IN ", function.name, ": LENGTH OF val ARGUMENT MUST BE IDENTICAL TO LENGTH OF expect.error ARGUMENT:\nHERE IT IS: ", base::length(val), " VERSUS ", base::length(expect.error))
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE)
}
}
if( ! is.null(thread.nb) & is.null(res.path)){
tempo.cat <- paste0("ERROR IN ", function.name, ": res.path ARGUMENT MUST BE SPECIFIED IF thread.nb ARGUMENT IS NOT NULL")
stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE)
}
if(is.null(res.path) & export == TRUE){
tempo.cat <- paste0("ERROR IN ", function.name, ": res.path ARGUMENT MUST BE SPECIFIED IF export ARGUMENT TRUE")
stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE)
}
if( ! is.null(thread.nb) & export == FALSE){
export <- TRUE
tempo.cat <- paste0("WARNING FROM ", function.name, ": export ARGUMENT CONVERTED TO TRUE BECAUSE thread.nb ARGUMENT IS NOT NULL")
warning(paste0("\n", tempo.cat, "\n"), call. = FALSE)
}
# end second round of checking and data preparation
# package checking
fun_pack(req.package = c("lubridate"), lib.path = lib.path)
if( ! is.null(thread.nb)){
fun_pack(req.package = c("parallel"), lib.path = lib.path)
}
# end package checking
# declaration of special plot functions
sp.plot.fun <- c("fun_gg_scatter", "fun_gg_bar", "fun_gg_boxplot")
# end declaration of special plot functions
# main code
2088
ini.warning.length <- base::options()$warning.length
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
warn <- NULL
warn.count <- 0
cat("\nfun_test JOB IGNITION\n")
ini.date <- Sys.time()
ini.time <- as.numeric(ini.date) # time of process begin, converted into seconds
if(export == TRUE){
res.path <- paste0(res.path, "/fun_test_res_", trunc(ini.time))
if(dir.exists(res.path)){
tempo.cat <- paste0("ERROR IN ", function.name, ": FOLDER ALREADY EXISTS\n", res.path, "\nPLEASE RERUN ONCE")
stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
}else{
dir.create(res.path)
}
}
total.comp.nb <- prod(sapply(val, FUN = "length"))
cat(paste0("\nTHE TOTAL NUMBER OF TESTS IS: ", total.comp.nb, "\n"))
# creation of the txt instruction that includes several loops
loop.string <- NULL
end.loop.string <- NULL
fun.args <- NULL
fun.args2 <- NULL
error.values <- NULL
arg.values <- "list("
2112
for(i1 in 1:base::length(arg)){
2113
if(is.null(thread.nb)){
2114
2115
if(base::length(val[[i1]]) > 1){ # loop only if more than one value in base::length(val[[i1]])
loop.string <- paste0(loop.string, "for(i", i1, " in 1:", base::length(val[[i1]]), "){")
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
end.loop.string <- paste0(end.loop.string, "}")
}
}else{
loop.string <- "for(i in x){"
end.loop.string <- "}"
}
fun.args <- paste0(
fun.args, 
ifelse(i1 == 1, "", ", "), 
arg[i1], 
" = val[[", 
i1, 
"]][[", 
if(is.null(thread.nb)){
2130
if(base::length(val[[i1]]) > 1){
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
paste0("i", i1)
}else{
"1" # a unique element in val[[i1]]
}
}else{
paste0("i.list[[", i1, "]][i]")
}, 
"]]"
)
fun.args2 <- paste0(
fun.args2, 
ifelse(i1 == 1, "", ", "), 
arg[i1], 
" = val[[", 
i1, 
"]][[', ", 
if(is.null(thread.nb)){
2148
if(base::length(val[[i1]]) > 1){
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
paste0("i", i1)
}else{
"1" # a unique element in val[[i1]]
}
}else{
paste0("i.list[[", i1, "]][i]")
}, 
", ']]"
)
arg.values <- paste0(
arg.values, 
"val[[", i1, "]][[", 
if(is.null(thread.nb)){
2162
if(base::length(val[[i1]]) > 1){
2163
2164
2165
2166
2167
2168
2169
2170
paste0("i", i1)
}else{
"1" # a unique element in val[[i1]]
}
}else{
paste0("i.list[[", i1, "]][i]")
}, 
"]]", 
2171
ifelse(i1 == base::length(arg), "", ", ")
2172
2173
2174
2175
2176
2177
)
error.values <- paste0(
error.values, 
ifelse(i1 == 1, "", " | "), 
"expect.error[[", i1, "]][[", 
if(is.null(thread.nb)){
2178
if(base::length(expect.error[[i1]]) > 1){
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
paste0("i", i1)
}else{
"1" # a unique element in expect.error[[i1]]
}
}else{
paste0("i.list[[", i1, "]][i]")
}, 
"]]"
)
}
arg.values <- paste0(arg.values, ")")
fun.test <- paste0(fun, "(", fun.args, ")")
fun.test2 <- paste0("paste0('", fun, "(", fun.args2, ")')")
# plot title for special plot functions
if(plot.fun == TRUE){
plot.kind <- "classic"
if(fun %in% sp.plot.fun){
plot.kind <- "special"
if(any(arg %in% "title")){ # this is for the special functions
tempo.match <- regmatches(x = fun.test, m = regexpr(text = fun.test, pattern = "title = .+[,)]"))
tempo.match <- substring(tempo.match , 1, nchar(tempo.match) - 1)
fun.test <- sub(x = fun.test, pattern = tempo.match, replacement = paste0(tempo.match, "\ntempo.title"))
}else{
fun.test <- sub(x = fun.test, pattern = ")$", replacement = ", title = tempo.title)")
}
}
}
# end plot title for special plot functions
kind <- character()
problem <- logical()
expected.error <- logical()
res <- character()
count <- 0
print.count.loop <- 0
plot.count <- 0
2214
if(base::length(arg) == 1){
2215
data <- data.frame()
2216
2217
}else{ # base::length(arg) == 0 already tested above
data <- data.frame(t(vector("character", base::length(arg))), stringsAsFactors = FALSE)[-1, ] # -1 to remove the single row created and to have an empty data frame with base::length(arg) columns
2218
2219
2220
2221
2222
}
code <- paste(
loop.string, '
count <- count + 1
print.count.loop <- print.count.loop + 1
2223
arg.values.print <- eval(parse(text = arg.values)) # recover the list of the i1 compartment
2224
2225
for(j3 in 1:base::length(arg.values.print)){ # WARNING: do not use i1, i2 etc., here because already in loop.string
tempo.capt <- capture.output(tempo.error <- fun_get_message(data =  paste0("paste(arg.values.print[[", j3, "]])"), kind = "error", header = FALSE, env = get(env.name, env = sys.nframe(), inherit = FALSE))) # collapsing arg.values sometimes does not work (with function for instance)
2226
if( ! is.null(tempo.error)){
2227
arg.values.print[[j3]] <- paste0("SPECIAL VALUE OF CLASS ", base::class(arg.values.print[[j3]]), " AND TYPE ", base::typeof(arg.values.print[[j3]]))
2228
2229
2230
}
}
data <- rbind(data, as.character(sapply(arg.values.print, FUN = "paste", collapse = " ")), stringsAsFactors = FALSE) # each colum is a test
2231
2232
tempo.capt <- capture.output(tempo.try.error <- fun_get_message(data = eval(parse(text = fun.test2)), kind = "error", header = FALSE, env = get(env.name, env = sys.nframe(), inherit = FALSE))) # data argument needs a character string but eval(parse(text = fun.test2)) provides it (eval parse replace the i1, i2, etc., by the correct values, meaning that only val is required in the env.name environment)
tempo.capt <- capture.output(tempo.try.warning <- fun_get_message(data = eval(parse(text = fun.test2)), kind = "warning", header = FALSE, env = get(env.name, env = sys.nframe(), inherit = FALSE), print.no = TRUE)) # data argument needs a character string but eval(parse(text = fun.test2)) provides it (eval parse replace the i1, i2, etc., by the correct values, meaning that only val is required in the env.name environment)
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
if( ! is.null(expect.error)){
expected.error <- c(expected.error, eval(parse(text = error.values)))
}
if( ! is.null(tempo.try.error)){
kind <- c(kind, "ERROR")
problem <- c(problem, TRUE)
res <- c(res, tempo.try.error)
}else{
if( ! is.null(tempo.try.warning)){
kind <- c(kind, "WARNING")
problem <- c(problem, FALSE)
res <- c(res, tempo.try.warning)
}else{
kind <- c(kind, "OK")
problem <- c(problem, FALSE)
res <- c(res, "")
}
if(plot.fun == TRUE){
invisible(dev.set(window.nb))
plot.count <- plot.count + 1
tempo.title <- paste0("test_", sprintf(paste0("%0", nchar(total.comp.nb), "d"), ifelse(is.null(thread.nb), count, x[count])))
if(plot.kind == "classic"){
eval(parse(text = fun.test))
tempo <- fun_post_plot(corner.text = tempo.title)
}else if(plot.kind == "special"){
eval(parse(text = fun.test))
}else{
tempo.cat <- paste0("INTERNAL CODE ERROR 1 IN ", function.name, ": CODE HAS TO BE MODIFIED")
stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
}
}
}
if(print.count.loop == print.count){
print.count.loop <- 0
tempo.time <- as.numeric(Sys.time())
tempo.lapse <- round(lubridate::seconds_to_period(tempo.time - ini.time))
2269
final.loop <- (tempo.time - ini.time) / count * ifelse(is.null(thread.nb), total.comp.nb, base::length(x)) # expected duration in seconds # intra nb.compar loop lapse: time lapse / cycles done * cycles remaining
2270
final.exp <- as.POSIXct(final.loop, origin = ini.date)
2271
cat(paste0(ifelse(is.null(thread.nb), "\n", paste0("\nIN PROCESS ", process.id, " | ")), "LOOP ", format(count, big.mark=","), " / ", format(ifelse(is.null(thread.nb), total.comp.nb, base::length(x)), big.mark=","), " | TIME SPENT: ", tempo.lapse, " | EXPECTED END: ", final.exp))
2272
}
2273
if(count == ifelse(is.null(thread.nb), total.comp.nb, base::length(x))){
2274
2275
tempo.time <- as.numeric(Sys.time())
tempo.lapse <- round(lubridate::seconds_to_period(tempo.time - ini.time))
2276
cat(paste0(ifelse(is.null(thread.nb), "\nLOOP PROCESS ENDED | ", paste0("\nPROCESS ", process.id, " ENDED | ")), "LOOP ", format(count, big.mark=","), " / ", format(ifelse(is.null(thread.nb), total.comp.nb, base::length(x)), big.mark=","), " | TIME SPENT: ", tempo.lapse, "\n\n"))
2277
2278
2279
2280
2281
2282
2283
}
', 
end.loop.string
)
# end creation of the txt instruction that includes several loops
if( ! is.null(thread.nb)){
# list of i numbers that will be split
2284
2285
i.list <- vector("list", base::length(val)) # positions to split in parallel jobs
for(i2 in 1:base::length(arg)){
2286
if(i2 == 1){
2287
2288
2289
tempo.divisor <- total.comp.nb / base::length(val[[i2]])
i.list[[i2]] <- rep(1:base::length(val[[i2]]), each = as.integer(tempo.divisor))
tempo.multi <- base::length(val[[i2]])
2290
}else{
2291
2292
2293
tempo.divisor <- tempo.divisor / base::length(val[[i2]])
i.list[[i2]] <- rep(rep(1:base::length(val[[i2]]), each = as.integer(tempo.divisor)), time = as.integer(tempo.multi))
tempo.multi <- tempo.multi * base::length(val[[i2]])
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
}
}
# end list of i numbers that will be split
tempo.cat <- paste0("PARALLELIZATION INITIATED AT: ", ini.date)
cat(paste0("\n", tempo.cat, "\n"))
tempo.thread.nb = parallel::detectCores(all.tests = FALSE, logical = TRUE) # detect the number of threads
if(tempo.thread.nb < thread.nb){
thread.nb <- tempo.thread.nb
}
tempo.cat <- paste0("NUMBER OF THREADS USED: ", thread.nb)
cat(paste0("\n    ", tempo.cat, "\n"))
Clust <- parallel::makeCluster(thread.nb, outfile = paste0(res.path, "/fun_test_parall_log.txt")) # outfile to print or cat during parallelization (only possible in a file, outfile = "" do not work on windows)
tempo.cat <- paste0("SPLIT OF TEST NUMBERS IN PARALLELISATION:")
cat(paste0("\n    ", tempo.cat, "\n"))
cluster.list <- parallel::clusterSplit(Clust, 1:total.comp.nb) # split according to the number of cluster
str(cluster.list) # using print(str()) add a NULL below the result
cat("\n")
paral.output.list <- parallel::clusterApply( # paral.output.list is a list made of thread.nb compartments, each made of n / thread.nb (mat theo column number) compartment. Each compartment receive the corresponding results of fun_permut(), i.e., data (permuted mat1.perm), warning message, cor (final correlation) and count (number of permutations)
cl = Clust,
x = cluster.list,
function.name = function.name, 
instruction = instruction, 
thread.nb = thread.nb, 
print.count = print.count, 
total.comp.nb = total.comp.nb, 
sp.plot.fun = sp.plot.fun,
i.list = i.list, 
fun.tested = fun,
arg.values = arg.values,
fun.test = fun.test,
fun.test2 = fun.test2,
kind = kind,
problem = problem,
res = res,
count = count,
plot.count = plot.count,
data = data,
code = code,
plot.fun = plot.fun, 
res.path = res.path, 
lib.path = lib.path, 
cute.path = cute.path, 
fun = function(
x, 
function.name, 
instruction, 
thread.nb, 
print.count, 
total.comp.nb, 
sp.plot.fun, 
i.list, 
fun.tested, 
arg.values, 
fun.test, 
fun.test2, 
kind, 
problem, 
res, 
count, 
plot.count, 
data, 
code, 
plot.fun, 
res.path, 
lib.path, 
cute.path
){
# check again: very important because another R
process.id <- Sys.getpid()
2363
cat(paste0("\nPROCESS ID ", process.id, " -> TESTS ", x[1], " TO ", x[base::length(x)], "\n"))
2364
2365
2366
2367
2368
source(cute.path, local = .GlobalEnv)
fun_pack(req.package = "lubridate", lib.path = lib.path, load = TRUE) # load = TRUE to be sure that functions are present in the environment. And this prevent to use R.lib.path argument of fun_python_pack()
# end check again: very important because another R
# plot management
if(plot.fun == TRUE){
2369
pdf(file = paste0(res.path, "/plots_from_fun_test_", x[1], ifelse(base::length(x) == 1, ".pdf", paste0("-", x[base::length(x)], ".pdf"))))
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
}else{
pdf(file = NULL) # send plots into a NULL file, no pdf file created
}
window.nb <- dev.cur()
invisible(dev.set(window.nb))
# end plot management
# new environment
env.name <- paste0("env", ini.time)
if(exists(env.name, where = -1)){ # verify if still ok when fun_test() is inside a function
tempo.cat <- paste0("ERROR IN ", function.name, ": ENVIRONMENT env.name ALREADY EXISTS. PLEASE RERUN ONCE")
stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
}else{
assign(env.name, new.env())
assign("val", val, envir = get(env.name, env = sys.nframe(), inherit = FALSE)) # var replaced by val
}
# end new environment
ini.date <- Sys.time()
ini.time <- as.numeric(ini.date) # time of process begin, converted into 
print.count.loop <- 0
suppressMessages(suppressWarnings(eval(parse(text = code))))
colnames(data) <- arg
if( ! is.null(expect.error)){
data <- data.frame(data, kind = kind, problem = problem, expected.error = expected.error, message = res, stringsAsFactors = FALSE)
}else{
data <- data.frame(data, kind = kind, problem = problem, message = res, stringsAsFactors = FALSE)
}
row.names(data) <- paste0("test_", sprintf(paste0("%0", nchar(total.comp.nb), "d"), x))
sys.info <- sessionInfo()
sys.info$loadedOnly <- sys.info$loadedOnly[order(names(sys.info$loadedOnly))] # sort the packages
invisible(dev.off(window.nb))
rm(env.name) # optional, because should disappear at the end of the function execution
# output
output <- list(fun = fun, data = data, instruction = instruction, sys.info = sys.info)
2403
save(output, file = paste0(res.path, "/fun_test_", x[1], ifelse(base::length(x) == 1, ".RData", paste0("-", x[base::length(x)], ".RData"))))
2404
2405
2406
2407
if(plot.fun == TRUE & plot.count == 0){
warn.count <- warn.count + 1
tempo.warn <- paste0("(", warn.count,") IN PROCESS ", process.id, ": NO PDF PLOT BECAUSE ONLY ERRORS REPORTED")
warn <- paste0(ifelse(is.null(warn), tempo.warn, paste0(warn, "\n\n", tempo.warn)))
2408
file.remove(paste0(res.path, "/plots_from_fun_test_", x[1], ifelse(base::length(x) == 1, ".pdf", paste0("-", x[base::length(x)], ".pdf"))))
2409
2410
2411
2412
}
table.out <- as.matrix(output$data)
# table.out[table.out == ""] <- " " # does not work # because otherwise read.table() converts "" into NA
table.out <- gsub(table.out, pattern = "\n", replacement = " ")
2413
write.table(table.out, file = paste0(res.path, "/table_from_fun_test_", x[1], ifelse(base::length(x) == 1, ".txt", paste0("-", x[base::length(x)], ".txt"))), row.names = TRUE, col.names = NA, append = FALSE, quote = FALSE, sep = "\t", eol = "\n")
2414
2415
2416
2417
}
)
parallel::stopCluster(Clust)
# txt files assembly
2418
2419
2420
if(base::length(cluster.list) > 1){
for(i2 in 1:base::length(cluster.list)){
tempo.name <- paste0(res.path, "/table_from_fun_test_", min(cluster.list[[i2]], na.rm = TRUE), ifelse(base::length(cluster.list[[i2]]) == 1, ".txt", paste0("-", max(cluster.list[[i2]], na.rm = TRUE), ".txt")))
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
tempo <- read.table(file = tempo.name, header = TRUE, stringsAsFactors = FALSE, sep = "\t", row.names = 1, comment.char = "", colClasses = "character") #  row.names = 1 (1st column) because now read.table() adds a NA in the header if the header starts by a tabulation, comment.char = "" because colors with #, colClasses = "character" otherwise convert "" (from NULL) into NA
file.remove(tempo.name)
if(i2 == 1){
final.file <- tempo
}else{
final.file <- rbind(final.file, tempo, stringsAsFactors = TRUE)
}
}
write.table(final.file, file = paste0(res.path, "/table_from_fun_test_1-", total.comp.nb, ".txt"), row.names = TRUE, col.names = NA, append = FALSE, quote = FALSE, sep = "\t", eol = "\n")
if( ! is.null(expect.error)){
final.file <- final.file[ ! final.file$problem == final.file$expected.error, ]
if(nrow(final.file) == 0){
cat(paste0("NO DISCREPANCY BETWEEN EXPECTED AND OBSERVED ERRORS\n\n"))
}else{
cat(paste0("DISCREPANCIES BETWEEN EXPECTED AND OBSERVED ERRORS (SEE THE discrepancy_table_from_fun_test_1-", total.comp.nb, ".txt FILE)\n\n"))
write.table(final.file, file = paste0(res.path, "/discrepancy_table_from_fun_test_1-", total.comp.nb, ".txt"), row.names = TRUE, col.names = NA, append = FALSE, quote = FALSE, sep = "\t", eol = "\n")
}
}
}
# end txt files assembly
}else{
# plot management
if(plot.fun == TRUE){
pdf(file = paste0(res.path, "/plots_from_fun_test_1", ifelse(total.comp.nb == 1, ".pdf", paste0("-", total.comp.nb, ".pdf"))))
}else{
pdf(file = NULL) # send plots into a NULL file, no pdf file created
}
window.nb <- dev.cur()
invisible(dev.set(window.nb))
# end plot management
# new environment
env.name <- paste0("env", ini.time)
if(exists(env.name, where = -1)){
tempo.cat <- paste0("ERROR IN ", function.name, ": ENVIRONMENT env.name ALREADY EXISTS. PLEASE RERUN ONCE")
stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
}else{
assign(env.name, new.env())
assign("val", val, envir = get(env.name, env = sys.nframe(), inherit = FALSE)) # var replaced by val
}
# end new environment
suppressMessages(suppressWarnings(eval(parse(text = code))))
colnames(data) <- arg
expect.data <- data.frame()
if( ! is.null(expect.error)){
data <- data.frame(data, kind = kind, problem = problem, expected.error = expected.error, message = res, stringsAsFactors = FALSE)
}else{
data <- data.frame(data, kind = kind, problem = problem, message = res, stringsAsFactors = FALSE)
}
row.names(data) <- paste0("test_", sprintf(paste0("%0", nchar(total.comp.nb), "d"), 1:total.comp.nb))
sys.info <- sessionInfo()
sys.info$loadedOnly <- sys.info$loadedOnly[order(names(sys.info$loadedOnly))] # sort the packages
invisible(dev.off(window.nb))
rm(env.name) # optional, because should disappear at the end of the function execution
# output
output <- list(fun = fun, data = data, instruction = instruction, sys.info = sys.info)
if(plot.fun == TRUE & plot.count == 0){
warn.count <- warn.count + 1
tempo.warn <- paste0("(", warn.count,") NO PDF PLOT BECAUSE ONLY ERRORS REPORTED")
warn <- paste0(ifelse(is.null(warn), tempo.warn, paste0(warn, "\n\n", tempo.warn)))
file.remove(paste0(res.path, "/plots_from_fun_test_1", ifelse(total.comp.nb == 1, ".pdf", paste0("-", total.comp.nb, ".pdf"))))
}
if( ! is.null(expect.error)){
expect.data <- output$data[ ! output$data$problem == output$data$expected.error, ]
if(nrow(expect.data) == 0){
cat(paste0("NO DISCREPANCY BETWEEN EXPECTED AND OBSERVED ERRORS\n\n"))
}else{
cat(paste0("DISCREPANCIES BETWEEN EXPECTED AND OBSERVED ERRORS (SEE THE ", if(export == TRUE){paste0("discrepancy_table_from_fun_test_1", ifelse(total.comp.nb == 1, "", paste0("-", total.comp.nb)), ".txt FILE")}else{"$data RESULT"}, ")\n\n"))
if(export == TRUE){
expect.data <- as.matrix(expect.data)
expect.data <- gsub(expect.data, pattern = "\n", replacement = "  ")
write.table(expect.data, file = paste0(res.path, "/discrepancy_table_from_fun_test_1", ifelse(total.comp.nb == 1, ".txt", paste0("-", total.comp.nb, ".txt"))), row.names = TRUE, col.names = NA, append = FALSE, quote = FALSE, sep = "\t", eol = "\n")
}
}
}
if( ! is.null(warn)){
2496
base::options(warning.length = 8170)
2497
on.exit(warning(paste0("FROM ", function.name, ":\n\n", warn), call. = FALSE))
2498
on.exit(exp = base::options(warning.length = ini.warning.length), add = TRUE)
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
}
if(export == TRUE){
save(output, file = paste0(res.path, "/fun_test_1", ifelse(total.comp.nb == 1, ".RData", paste0("-", total.comp.nb, ".RData"))))
table.out <- as.matrix(output$data)
table.out <- gsub(table.out, pattern = "\n", replacement = "  ")
write.table(table.out, file = paste0(res.path, "/table_from_fun_test_1", ifelse(total.comp.nb == 1, ".txt", paste0("-", total.comp.nb, ".txt"))), row.names = TRUE, col.names = NA, append = FALSE, quote = FALSE, sep = "\t", eol = "\n")
}else{
return(output)
}
}
end.date <- Sys.time()
end.time <- as.numeric(end.date)
total.lapse <- round(lubridate::seconds_to_period(end.time - ini.time))
cat(paste0("fun_test JOB END\n\nTIME: ", end.date, "\n\nTOTAL TIME LAPSE: ", total.lapse, "\n\n\n"))
}


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


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


fun_name_change <- function(data1, data2, added.string = "_modif"){
# AIM
# this function allow to check if a vector of character strings, like column names of a data frame, has elements present in another vector (vector of reserved words or column names of another data frame before merging)
# ARGUMENTS
# data1: vector of character strings to check and modify
# data2: reference vector of character strings
# added.string: string added at the end of the modified string in data1 if present in data2
# RETURN
# a list containing
# $data: the modified data1 (in the same order as in the initial data1)
# $ini: the initial elements before modification. NULL if no modification
# $post: the modified elements in the same order as in ini. NULL if no modification
# REQUIRED PACKAGES
# none
# REQUIRED FUNCTIONS FROM CUTE_LITTLE_R_FUNCTION
# fun_check()
# EXAMPLES
# obs1 <- c("A", "B", "C", "D") ; obs2 <- c("A", "C") ; fun_name_change(obs1, obs2)
# obs1 <- c("A", "B", "C", "C_modif1", "D") ; obs2 <- c("A", "A_modif1", "C") ; fun_name_change(obs1, obs2) # the function checks that the new names are neither in obs1 nor in obs2 (increment the number after the added string)
# DEBUGGING
# data1 = c("A", "B", "C", "D") ; data2 <- c("A", "C") ; added.string = "_modif" # for function debugging
# function name
function.name <- paste0(as.list(match.call(expand.dots = FALSE))[[1]], "()")
# end function name
# required function checking
if(length(utils::find("fun_check", mode = "function")) == 0){
tempo.cat <- paste0("ERROR IN ", function.name, ": REQUIRED fun_check() FUNCTION IS MISSING IN THE R ENVIRONMENT")
stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
}
# end required function checking
# argument checking
arg.check <- NULL #
text.check <- NULL #
checked.arg.names <- NULL # for function debbuging: used by r_debugging_tools
ee <- expression(arg.check <- c(arg.check, tempo$problem) , text.check <- c(text.check, tempo$text) , checked.arg.names <- c(checked.arg.names, tempo$object.name))
tempo <- fun_check(data = data1, class = "vector", mode = "character", fun.name = function.name) ; eval(ee)
tempo <- fun_check(data = data2, class = "vector", mode = "character", fun.name = function.name) ; eval(ee)
tempo <- fun_check(data = added.string, class = "vector", mode = "character", length = 1, fun.name = function.name) ; eval(ee)
if(any(arg.check) == TRUE){
stop(paste0("\n\n================\n\n", paste(text.check[arg.check], collapse = "\n"), "\n\n================\n\n"), call. = FALSE) #
}
Gael's avatar
tempo    
Gael committed
2563
# source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.7/r_debugging_tools-v1.7.R") ; eval(parse(text = str_basic_arg_check_dev)) ; eval(parse(text = str_arg_check_with_fun_check_dev)) # activate this line and use the function (with no arguments left as NULL) to check arguments status and if they have been checked using fun_check()
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
# end argument checking
# main code
ini <- NULL
post <- NULL
if(any(data1 %in% data2)){
tempo.names <- data1[data1 %in% data2]
ini <- NULL
post <- NULL
for(i2 in 1:length(tempo.names)){
count <- 0
tempo <- tempo.names[i2]
while(any(tempo %in% data2) | any(tempo %in% data1)){
count <- count + 1
tempo <- paste0(tempo.names[i2], "_modif", count)
}
data1[data1 %in% tempo.names[i2]] <- paste0(tempo.names[i2], "_modif", count)
if(count != 0){
ini <- c(ini, tempo.names[i2])
post <- c(post, paste0(tempo.names[i2], "_modif", count))
}
}
data <- data1
}else{
data <- data1
}
output <- list(data = data, ini = ini, post = post)
return(output)
}


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


fun_df_remod <- function(
data, 
quanti.col.name = "quanti", 
quali.col.name = "quali"
){
# AIM
# if the data frame is made of numeric columns, a new data frame is created, with the 1st column gathering all the numeric values, and the 2nd column being the name of the columns of the initial data frame. If row names were present in the initial data frame, then a new ini_rowname column is added with the names of the rows

 
# If the data frame is made of one numeric column and one character or factor column, a new data frame is created, with the new columns corresponding to the split numeric values (according to the character column). NA are added a the end of each column to have the same number of rows. BEWARE: in such data frame, rows are not individuals. This means that in the example below, values 10 and 20 are associated on the same row but that means nothing in term of association

 

# ARGUMENTS
# data: data frame to convert
# quanti.col.name: optional name for the quanti column of the new data frame
# quali.col.name: optional name for the quali column of the new data frame
# RETURN
# the modified data frame
# REQUIRED PACKAGES
# none
# REQUIRED FUNCTIONS FROM CUTE_LITTLE_R_FUNCTION
# fun_check()
# EXAMPLES
# obs <- data.frame(col1 = (1:4)*10, col2 = c("A", "B", "A", "A"), stringsAsFactors = TRUE) ; obs ; fun_df_remod(obs)
# obs <- data.frame(col1 = (1:4)*10, col2 = 5:8, stringsAsFactors = TRUE) ; obs ; fun_df_remod(obs, quanti.col.name = "quanti", quali.col.name = "quali")
# obs <- data.frame(col1 = (1:4)*10, col2 = 5:8, stringsAsFactors = TRUE) ; rownames(obs) <- paste0("row", 1:4) ; obs ; fun_df_remod(obs, quanti.col.name = "quanti", quali.col.name = "quali")
# DEBUGGING
# data = data.frame(a = 1:3, b = 4:6, stringsAsFactors = TRUE) ; quanti.col.name = "quanti" ; quali.col.name = "quali" # for function debugging
# data = data.frame(a = 1:3, b = 4:6, c = 11:13, stringsAsFactors = TRUE) ; quanti.col.name = "quanti" ; quali.col.name = "quali" # for function debugging
# data = data.frame(a = 1:3, b = letters[1:3], stringsAsFactors = TRUE) ; quanti.col.name = "quanti" ; quali.col.name = "quali" # for function debugging
# data = data.frame(a = 1:3, b = letters[1:3], stringsAsFactors = TRUE) ; quanti.col.name = "TEST" ; quali.col.name = "quali" # for function debugging
# data = data.frame(b = letters[1:3], a = 1:3, stringsAsFactors = TRUE) ; quanti.col.name = "quanti" ; quali.col.name = "quali" # for function debugging
# data = data.frame(b = c("e", "e", "h"), a = 1:3, stringsAsFactors = TRUE) ; quanti.col.name = "quanti" ; quali.col.name = "quali" # for function debugging
# function name
function.name <- paste0(as.list(match.call(expand.dots = FALSE))[[1]], "()")
# end function name
# required function checking
if(length(utils::find("fun_check", mode = "function")) == 0){
tempo.cat <- paste0("ERROR IN ", function.name, ": REQUIRED fun_check() FUNCTION IS MISSING IN THE R ENVIRONMENT")
stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
}
# end required function checking
# argument checking
# argument checking without fun_check()
if( ! any(class(data) %in% "data.frame")){
tempo.cat <- paste0("ERROR IN ", function.name, ": THE data ARGUMENT MUST BE A DATA FRAME")
stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
}
# end argument checking without fun_check()
# argument checking with fun_check()
arg.check <- NULL #
text.check <- NULL #
checked.arg.names <- NULL # for function debbuging: used by r_debugging_tools
ee <- expression(arg.check <- c(arg.check, tempo$problem) , text.check <- c(text.check, tempo$text) , checked.arg.names <- c(checked.arg.names, tempo$object.name))
tempo <- fun_check(data = quanti.col.name, class = "character", length = 1, fun.name = function.name) ; eval(ee)
tempo <- fun_check(data = quali.col.name, class = "character", length = 1, fun.name = function.name) ; eval(ee)
if(any(arg.check) == TRUE){
stop(paste0("\n\n================\n\n", paste(text.check[arg.check], collapse = "\n"), "\n\n================\n\n"), call. = FALSE) #
}
# end argument checking with fun_check()
Gael's avatar
tempo    
Gael committed
2658
# source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.7/r_debugging_tools-v1.7.R") ; eval(parse(text = str_basic_arg_check_dev)) ; eval(parse(text = str_arg_check_with_fun_check_dev)) # activate this line and use the function (with no arguments left as NULL) to check arguments status and if they have been checked using fun_check()
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
# end argument checking
# main code
tempo.factor <- unlist(lapply(data, class))
for(i in 1:length(tempo.factor)){ # convert factor columns as character
if(all(tempo.factor[i] == "factor")){
data[, i] <- as.character(data[, i])
}
}
tempo.factor <- unlist(lapply(data, mode))
if(length(data) == 2){
2669
if( ! ((base::mode(data[, 1]) == "character" & base::mode(data[, 2]) == "numeric") | base::mode(data[, 2]) == "character" & base::mode(data[, 1]) == "numeric" | base::mode(data[, 2]) == "numeric" & base::mode(data[, 1]) == "numeric") ){
2670
2671
2672
tempo.cat <- paste0("ERROR IN ", function.name, ": IF data ARGUMENT IS A DATA FRAME MADE OF 2 COLUMNS, EITHER A COLUMN MUST BE NUMERIC AND THE OTHER CHARACTER, OR THE TWO COLUMNS MUST BE NUMERIC")
stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
}
2673
if((base::mode(data[, 1]) == "character" | base::mode(data[, 2]) == "character") & (quanti.col.name != "quanti" | quali.col.name != "quali")){
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
tempo.cat <- paste0("ERROR IN ", function.name, ": IMPROPER quanti.col.name OR quali.col.name RESETTINGS. THESE ARGUMENTS ARE RESERVED FOR DATA FRAMES MADE OF n NUMERIC COLUMNS ONLY")
stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
}
}else{
if( ! all(tempo.factor %in% "numeric")){
tempo.cat <- paste0("ERROR IN ", function.name, ": IF data ARGUMENT IS A DATA FRAME MADE OF ONE COLUMN, OR MORE THAN 2 COLUMNS, THESE COLUMNS MUST BE NUMERIC")
stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
}
}
if(( ! any(tempo.factor %in% "character")) & is.null(names(data))){
tempo.cat <- paste0("ERROR IN ", function.name, ": NUMERIC DATA FRAME in the data ARGUMENT MUST HAVE COLUMN NAMES")
stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
}
if(all(tempo.factor %in% "numeric")){ # transfo 1
quanti <- NULL
for(i in 1:length(data)){
quanti <-c(quanti, data[, i])
}
quali <- rep(names(data), each = nrow(data))
output.data <- data.frame(quanti, quali, stringsAsFactors = TRUE)
names(output.data) <- c(quanti.col.name, quali.col.name)
# add the ini_rowname column
ini.rownames <- rownames(data)
tempo.data <- data
rownames(tempo.data) <- NULL
null.rownames <- (tempo.data)
if( ! identical(ini.rownames, null.rownames)){
ini_rowname <- rep(ini.rownames, times = ncol(data))
output.data <- cbind(output.data, ini_rowname, stringsAsFactors = TRUE)
}
}else{ # transfo 2
if(class(data[, 1]) == "character"){
data <- cbind(data[2], data[1], stringsAsFactors = TRUE)
}
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, stringsAsFactors = TRUE)
}
return(output.data)
}




######## fun_round() #### rounding number if decimal present


fun_round <- function(data, dec.nb = 2, after.lead.zero = TRUE){
# AIM
# round a vector of values, if decimal, with the desired number of decimal digits after the decimal leading zeros
# WARNINGS
# Work well with numbers as character strings, but not always with numerical numbers because of the floating point
# Numeric values are really truncated from a part of their decimal digits, whatever options(digits) settings
# See ?.Machine or https://stackoverflow.com/questions/5173692/how-to-return-number-of-decimal-places-in-r, with the interexting formula: abs(x - round(x)) > .Machine$double.eps^0.5
# ARGUMENTS
# data: a vector of numbers (numeric or character mode)
# dec.nb: number of required decimal digits
# after.lead.zero: logical. If FALSE, rounding is performed for all the decimal numbers, whatever the leading zeros (e.g., 0.123 -> 0.12 and 0.00128 -> 0.00). If TRUE, dec.nb are taken after the leading zeros (e.g., 0.123 -> 0.12 and 0.00128 -> 0.0013)
# RETURN
# the modified vector
# REQUIRED PACKAGES
# none
# REQUIRED FUNCTIONS FROM CUTE_LITTLE_R_FUNCTION
# fun_check()
# EXAMPLES
# ini.options <- options()$digits ; options(digits = 8) ; cat(fun_round(data = c(NA, 10, 100.001, 333.0001254, 12312.1235), dec.nb = 2, after.lead.zero = FALSE), "\n\n") ; options(digits = ini.options)
# ini.options <- options()$digits ; options(digits = 8) ; cat(fun_round(data = c(NA, 10, 100.001, 333.0001254, 12312.1235), dec.nb = 2, after.lead.zero = TRUE), "\n\n") ; options(digits = ini.options)
# ini.options <- options()$digits ; options(digits = 8) ; cat(fun_round(data = c(NA, "10", "100.001", "333.0001254", "12312.1235"), dec.nb = 2, after.lead.zero = FALSE), "\n\n") ; options(digits = ini.options)
# ini.options <- options()$digits ; options(digits = 8) ; cat(fun_round(data = c(NA, "10", "100.001", "333.0001254", "12312.1235"), dec.nb = 2, after.lead.zero = TRUE), "\n\n") ; options(digits = ini.options)
# DEBUGGING
# data = data = c(10, 100.001, 333.0001254, 12312.1235) ; dec.nb = 2 ; after.lead.zero = FALSE # # for function debugging
# data = data = c("10", "100.001", "333.0001254", "12312.1235") ; dec.nb = 2 ; after.lead.zero = TRUE # # for function debugging
# function name
function.name <- paste0(as.list(match.call(expand.dots = FALSE))[[1]], "()")
# end function name
# required function checking
if(length(utils::find("fun_check", mode = "function")) == 0){
tempo.cat <- paste0("ERROR IN ", function.name, ": REQUIRED fun_check() FUNCTION IS MISSING IN THE R ENVIRONMENT")
stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
}
# end required function checking
# argument checking
# argument checking without fun_check()
if( ! (all(typeof(data) == "character") | all(typeof(data) == "double") | all(typeof(data) == "integer"))){
tempo.cat <- paste0("ERROR IN ", function.name, ": data ARGUMENT MUST BE A VECTOR OF NUMBERS (IN NUMERIC OR CHARACTER MODE)")
stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
}
# end argument checking without fun_check()
# argument checking with fun_check()
arg.check <- NULL #
text.check <- NULL #
checked.arg.names <- NULL # for function debbuging: used by r_debugging_tools
ee <- expression(arg.check <- c(arg.check, tempo$problem) , text.check <- c(text.check, tempo$text) , checked.arg.names <- c(checked.arg.names, tempo$object.name))
tempo <- fun_check(data = data, class = "vector", na.contain = TRUE, fun.name = function.name) ; eval(ee)
tempo <- fun_check(data = dec.nb, class = "vector", typeof = "integer", length = 1, double.as.integer.allowed = TRUE, neg.values = FALSE, fun.name = function.name) ; eval(ee)
tempo <- fun_check(data = after.lead.zero, class = "logical", length = 1, fun.name = function.name) ; eval(ee)
if(any(arg.check) == TRUE){
stop(paste0("\n\n================\n\n", paste(text.check[arg.check], collapse = "\n"), "\n\n================\n\n"), call. = FALSE) #
}
# end argument checking with fun_check()
Gael's avatar
tempo    
Gael committed
2776
# source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.7/r_debugging_tools-v1.7.R") ; eval(parse(text = str_basic_arg_check_dev)) ; eval(parse(text = str_arg_check_with_fun_check_dev)) # activate this line and use the function (with no arguments left as NULL) to check arguments status and if they have been checked using fun_check()
2777
2778
2779
# end argument checking
# main code
tempo <- grepl(x = data, pattern = "\\.") # detection of decimal numbers
2780
ini.mode <- base::mode(data)
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
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_mat_rotate() #### 90° clockwise matrix rotation


fun_mat_rotate <- function(data){
# AIM
# 90° clockwise matrix rotation
# applied twice, the function provide the mirror matrix, according to vertical and horizontal symmetry
# ARGUMENTS
# data: matrix (matrix class)
# RETURN
# the modified matrix
# REQUIRED PACKAGES
# none
# REQUIRED FUNCTIONS FROM CUTE_LITTLE_R_FUNCTION
# fun_check()
# EXAMPLES
# obs <- matrix(1:10, ncol = 1) ; obs ; fun_mat_rotate(obs)
# obs <- matrix(LETTERS[1:10], ncol = 5) ; obs ; fun_mat_rotate(obs)
# DEBUGGING
# data = matrix(1:10, ncol = 1)
# function name
function.name <- paste0(as.list(match.call(expand.dots = FALSE))[[1]], "()")
# end function name
# required function checking
if(length(utils::find("fun_check", mode = "function")) == 0){
tempo.cat <- paste0("ERROR IN ", function.name, ": REQUIRED fun_check() FUNCTION IS MISSING IN THE R ENVIRONMENT")
stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
}
# end required function checking
# argument checking
arg.check <- NULL #
text.check <- NULL #
checked.arg.names <- NULL # for function debbuging: used by r_debugging_tools
ee <- expression(arg.check <- c(arg.check, tempo$problem) , text.check <- c(text.check, tempo$text) , checked.arg.names <- c(checked.arg.names, tempo$object.name))
tempo <- fun_check(data = data, class = "matrix", fun.name = function.name) ; eval(ee)
if(any(arg.check) == TRUE){
stop(paste0("\n\n================\n\n", paste(text.check[arg.check], collapse = "\n"), "\n\n================\n\n"), call. = FALSE) #
}
Gael's avatar
tempo    
Gael committed
2844
# source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.7/r_debugging_tools-v1.7.R") ; eval(parse(text = str_basic_arg_check_dev)) ; eval(parse(text = str_arg_check_with_fun_check_dev)) # activate this line and use the function (with no arguments left as NULL) to check arguments status and if they have been checked using fun_check()
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
# end argument checking
# main code
for (i in 1:ncol(data)){data[,i] <- rev(data[,i])}
data <- t(data)
return(data)
}


######## fun_mat_num2color() #### convert a numeric matrix into hexadecimal color matrix


fun_mat_num2color <- function(
mat1, 
mat.hsv.h = TRUE, 
notch = 1, 
s = 1, 
v = 1, 
forced.color = NULL
){
# AIM
# convert a matrix made of numbers into a hexadecimal matrix for rgb colorization
# 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
# REQUIRED PACKAGES
# none
# REQUIRED FUNCTIONS FROM CUTE_LITTLE_R_FUNCTION
# fun_check()
# EXAMPLES
# mat1 = matrix(c(1,1,1,2,1,5,9,NA), ncol = 2) ; dimnames(mat1) <- list(LETTERS[1:4], letters[1:2]) ; fun_mat_num2color(mat1, mat.hsv.h = FALSE, notch = 1, s = 1, v = 1, forced.color = NULL)
# DEBUGGING
# mat1 = matrix(c(1,1,1,2,1,5,9,NA), ncol = 2) ; dimnames(mat1) <- list(LETTERS[1:4], letters[1:2]); mat.hsv.h = FALSE ; notch = 1 ; s = 1 ; v = 1 ; forced.color = c(hsv(1,1,1), hsv(0,0,0)) # for function debugging
# function name
function.name <- paste0(as.list(match.call(expand.dots = FALSE))[[1]], "()")
# end function name
# required function checking
if(length(utils::find("fun_check", mode = "function")) == 0){
tempo.cat <- paste0("ERROR IN ", function.name, ": REQUIRED fun_check() FUNCTION IS MISSING IN THE R ENVIRONMENT")
stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
}
# end required function checking
# argument checking
# argument checking with fun_check()
arg.check <- NULL #
text.check <- NULL #
checked.arg.names <- NULL # for function debbuging: used by r_debugging_tools
ee <- expression(arg.check <- c(arg.check, tempo$problem) , text.check <- c(text.check, tempo$text) , checked.arg.names <- c(checked.arg.names, tempo$object.name))
tempo <- fun_check(data = mat1, mode = "numeric", class = "matrix", na.contain = TRUE, neg.values = FALSE, fun.name = function.name) ; eval(ee)
tempo <- fun_check(data = mat.hsv.h, class = "logical", length = 1, fun.name = function.name) ; eval(ee)
tempo <- fun_check(data = notch, class = "vector", mode = "numeric", length = 1, prop = TRUE, fun.name = function.name) ; eval(ee)
tempo <- fun_check(data = s, class = "vector", mode = "numeric", length = 1, prop = TRUE, fun.name = function.name) ; eval(ee)
tempo <- fun_check(data = v, class = "vector", mode = "numeric", length = 1, prop = TRUE, fun.name = function.name) ; eval(ee)
if(any(arg.check) == TRUE){
stop(paste0("\n\n================\n\n", paste(text.check[arg.check], collapse = "\n"), "\n\n================\n\n"), call. = FALSE) #
}
# end argument checking with fun_check()
# argument checking without fun_check()
if(mat.hsv.h == TRUE & fun_check(data = mat1, mode = "numeric", prop = TRUE)$problem == TRUE){
tempo.cat <- paste0("ERROR IN ", function.name, ": mat1 ARGUMENT MUST BE A MATRIX OF PROPORTIONS SINCE THE mat.hsv.h ARGUMENT IS SET TO TRUE")
stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
}
if( ! is.null(forced.color)){
tempo <- fun_check(data = forced.color, class = "character")
if(any(tempo$problem == TRUE)){
paste0("\n\n================\n\n", paste(tempo$text[tempo$problem], collapse = "\n"))
stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
}
if( ! all(forced.color %in% colors() | grepl(pattern = "^#", forced.color))){ # check that all strings of forced.color start by #
tempo.cat <- paste0("ERROR IN ", function.name, ": forced.color ARGUMENT MUST BE A HEXADECIMAL COLOR VECTOR STARTING BY # AND/OR COLOR NAMES GIVEN BY colors()")
stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
}
}
# end argument checking without fun_check()
Gael's avatar
tempo    
Gael committed
2928
# source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.7/r_debugging_tools-v1.7.R") ; eval(parse(text = str_basic_arg_check_dev)) ; eval(parse(text = str_arg_check_with_fun_check_dev)) # activate this line and use the function (with no arguments left as NULL) to check arguments status and if they have been checked using fun_check()
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
# end argument checking
# main code
problem <- NULL
text.problem <- NULL
mat1.name <- deparse(substitute(mat1))
# change the scale of the plotted matrix
if(mat.hsv.h == TRUE){
if(any(min(mat1, na.rm = TRUE) < 0 | max(mat1, na.rm = TRUE) > 1, na.rm = TRUE)){
tempo.cat <- paste0("ERROR IN ", function.name, ": mat1 MUST BE MADE OF VALUES BETWEEN 0 AND 1 BECAUSE mat.hsv.h ARGUMENT SET TO TRUE")
stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
}
}else{
if(any(mat1 - floor(mat1) > 0, na.rm = TRUE) | any(mat1 == 0, na.rm = TRUE)){ # no need of isTRUE(all.equal()) because we do not require approx here but strictly 0, thus == is ok
tempo.cat <- paste0("ERROR IN ", function.name, ": mat1 MUST BE MADE OF INTEGER VALUES WITHOUT 0 BECAUSE mat.hsv.h ARGUMENT SET TO FALSE")
stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
}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("ERROR IN ", function.name, ": DUPLICATED VALUES AFTER USING notch (", paste(tempo.different.color[duplicated(tempo.different.color)], collapse = " "), "). TRY ANOTHER notch VALUE")
stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
}else if(length(different.color) != length(tempo.different.color)){
tempo.cat <- paste0("ERROR IN ", function.name, ": LENGTH OF different.color (", paste(different.color, collapse = " "), ") DIFFERENT FROM LENGTH OF tempo.different.color (", paste(tempo.different.color, collapse = " "), ")")
stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
}else{
for(i in 1:length(different.color)){
mat1[mat1 == different.color[i]] <- tempo.different.color[i] # no need of isTRUE(all.equal()) because different.color comes from mat1
}
}
}
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)){# no need of isTRUE(all.equal()) because character
tempo.cat <- paste0("ERROR IN ", function.name, ": THE ", hexa.values.to.change[i], " VALUE FROM hexa.values.to.change IS NOT REPRESENTED IN mat1 : ", paste(unique(as.vector(mat1)), collapse = " "))
stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
}else{
mat1[which(mat1 == hexa.values.to.change[i])] <- forced.color[i] # no need of isTRUE(all.equal()) because character
}
}
}
output <- list(mat1.name = mat1.name, colored.mat = mat1, problem = problem, text.problem = text.problem)
return(output)
}


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


fun_mat_op <- function(mat.list, kind.of.operation = "+"){
# AIM
# assemble several matrices of same dimensions by performing by case operation. For instance add the value of all the case 1 (row1 & column1) of the matrices and put it in the case 1 of a new matrix M, add the value of all the case 2 (row2 & column1) of the matrices and put it in the case 2 of a new matrix M, etc.
 
# c: case
# i: row number
# j: column number
# k: matrix number