cute_little_R_functions.R 866 KB
Newer Older
Gael  MILLOT's avatar
Gael MILLOT committed
2001
2002
2003
2004
2005
2006
2007
2008
# end check again: very important because another R
# plot management
if(plot.fun == TRUE){
pdf(file = paste0(res.path, "/plots_from_fun_test_", x[1], ifelse(length(x) == 1, ".pdf", paste0("-", x[length(x)], ".pdf"))))
}else{
pdf(file = NULL) # send plots into a NULL file, no pdf file created
}
window.nb <- dev.cur()
2009
invisible(dev.set(window.nb))
Gael  MILLOT's avatar
Gael MILLOT committed
2010
2011
2012
# end plot management
# new environment
env.name <- paste0("env", ini.time)
2013
if(exists(env.name, where = -1)){ # verify if still ok when fun_test() is inside a function
2014
2015
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 ==
Gael  MILLOT's avatar
Gael MILLOT committed
2016
2017
}else{
assign(env.name, new.env())
2018
assign("val", val, envir = get(env.name, env = sys.nframe(), inherit = FALSE)) # var replaced by val
Gael  MILLOT's avatar
Gael MILLOT committed
2019
2020
2021
2022
}
# end new environment
ini.date <- Sys.time()
ini.time <- as.numeric(ini.date) # time of process begin, converted into 
Gael  MILLOT's avatar
Gael MILLOT committed
2023
print.count.loop <- 0
Gael  MILLOT's avatar
Gael MILLOT committed
2024
2025
suppressMessages(suppressWarnings(eval(parse(text = code))))
colnames(data) <- arg
2026
2027
2028
if( ! is.null(expect.error)){
data <- data.frame(data, kind = kind, problem = problem, expected.error = expected.error, message = res, stringsAsFactors = FALSE)
}else{
Gael  MILLOT's avatar
Gael MILLOT committed
2029
data <- data.frame(data, kind = kind, problem = problem, message = res, stringsAsFactors = FALSE)
2030
}
Gael  MILLOT's avatar
Gael MILLOT committed
2031
row.names(data) <- paste0("test_", sprintf(paste0("%0", nchar(total.comp.nb), "d"), x))
Gael  MILLOT's avatar
Gael MILLOT committed
2032
sys.info <- sessionInfo()
2033
sys.info$loadedOnly <- sys.info$loadedOnly[order(names(sys.info$loadedOnly))] # sort the packages
Gael  MILLOT's avatar
Gael MILLOT committed
2034
2035
2036
invisible(dev.off(window.nb))
rm(env.name) # optional, because should disappear at the end of the function execution
# output
2037
output <- list(fun = fun, data = data, instruction = instruction, sys.info = sys.info)
Gael  MILLOT's avatar
Gael MILLOT committed
2038
2039
save(output, file = paste0(res.path, "/fun_test_", x[1], ifelse(length(x) == 1, ".RData", paste0("-", x[length(x)], ".RData"))))
if(plot.fun == TRUE & plot.count == 0){
Gael  MILLOT's avatar
Gael MILLOT committed
2040
warning(paste0("\nWARNING FROM ", function.name, " IN PROCESS ", process.id, ": NO PDF PLOT BECAUSE ONLY ERRORS REPORTED\n"), call. = FALSE)
Gael  MILLOT's avatar
Gael MILLOT committed
2041
2042
2043
file.remove(paste0(res.path, "/plots_from_fun_test_", x[1], ifelse(length(x) == 1, ".pdf", paste0("-", x[length(x)], ".pdf"))))
}
table.out <- as.matrix(output$data)
2044
# table.out[table.out == ""] <- " " # does not work # because otherwise read.table() converts "" into NA
Gael  MILLOT's avatar
Gael MILLOT committed
2045
2046
2047
2048
2049
table.out <- gsub(table.out, pattern = "\n", replacement = " ")
write.table(table.out, file = paste0(res.path, "/table_from_fun_test_", x[1], ifelse(length(x) == 1, ".txt", paste0("-", x[length(x)], ".txt"))), row.names = TRUE, col.names = NA, append = FALSE, quote = FALSE, sep = "\t", eol = "\n")
}
)
parallel::stopCluster(Clust)
2050
2051
2052
2053
# txt files assembly
if(length(cluster.list) > 1){
for(i2 in 1:length(cluster.list)){
tempo.name <- paste0(res.path, "/table_from_fun_test_", min(cluster.list[[i2]], na.rm = TRUE), ifelse(length(cluster.list[[i2]]) == 1, ".txt", paste0("-", max(cluster.list[[i2]], na.rm = TRUE), ".txt")))
2054
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
2055
2056
2057
2058
file.remove(tempo.name)
if(i2 == 1){
final.file <- tempo
}else{
2059
final.file <- rbind(final.file, tempo, stringsAsFactors = TRUE)
2060
2061
2062
}
}
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")
2063
2064
2065
2066
2067
2068
2069
2070
2071
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")
}
}
2072
2073
}
# end txt files assembly
Gael  MILLOT's avatar
Gael MILLOT committed
2074
2075
2076
2077
2078
2079
2080
2081
}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()
2082
invisible(dev.set(window.nb))
Gael  MILLOT's avatar
Gael MILLOT committed
2083
2084
2085
2086
# end plot management
# new environment
env.name <- paste0("env", ini.time)
if(exists(env.name, where = -1)){
2087
2088
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 ==
Gael  MILLOT's avatar
Gael MILLOT committed
2089
2090
}else{
assign(env.name, new.env())
2091
assign("val", val, envir = get(env.name, env = sys.nframe(), inherit = FALSE)) # var replaced by val
Gael  MILLOT's avatar
Gael MILLOT committed
2092
2093
}
# end new environment
Gael  MILLOT's avatar
Gael MILLOT committed
2094
2095
suppressMessages(suppressWarnings(eval(parse(text = code))))
colnames(data) <- arg
2096
2097
2098
2099
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{
Gael  MILLOT's avatar
Gael MILLOT committed
2100
data <- data.frame(data, kind = kind, problem = problem, message = res, stringsAsFactors = FALSE)
2101
}
Gael  MILLOT's avatar
Gael MILLOT committed
2102
2103
row.names(data) <- paste0("test_", sprintf(paste0("%0", nchar(total.comp.nb), "d"), 1:total.comp.nb))
sys.info <- sessionInfo()
2104
sys.info$loadedOnly <- sys.info$loadedOnly[order(names(sys.info$loadedOnly))] # sort the packages
Gael  MILLOT's avatar
Gael MILLOT committed
2105
2106
2107
invisible(dev.off(window.nb))
rm(env.name) # optional, because should disappear at the end of the function execution
# output
2108
output <- list(fun = fun, data = data, instruction = instruction, sys.info = sys.info)
Gael  MILLOT's avatar
Gael MILLOT committed
2109
if(plot.fun == TRUE & plot.count == 0){
Gael  MILLOT's avatar
Gael MILLOT committed
2110
warning(paste0("\nWARNING FROM ", function.name, ": NO PDF PLOT BECAUSE ONLY ERRORS REPORTED\n"), call. = FALSE)
Gael  MILLOT's avatar
Gael MILLOT committed
2111
file.remove(paste0(res.path, "/plots_from_fun_test_1", ifelse(total.comp.nb == 1, ".pdf", paste0("-", total.comp.nb, ".pdf"))))
Gael  MILLOT's avatar
Gael MILLOT committed
2112
}
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
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")
}
}
}
Gael  MILLOT's avatar
Gael MILLOT committed
2126
2127
2128
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)
2129
table.out <- gsub(table.out, pattern = "\n", replacement = "  ")
Gael  MILLOT's avatar
Gael MILLOT committed
2130
2131
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{
Gael  MILLOT's avatar
Gael MILLOT committed
2132
return(output)
Gael  MILLOT's avatar
Gael MILLOT committed
2133
}
Gael  MILLOT's avatar
Gael MILLOT committed
2134
}
Gael  MILLOT's avatar
Gael MILLOT committed
2135
2136
2137
end.date <- Sys.time()
end.time <- as.numeric(end.date)
total.lapse <- round(lubridate::seconds_to_period(end.time - ini.time))
2138
cat(paste0("fun_test JOB END\n\nTIME: ", end.date, "\n\nTOTAL TIME LAPSE: ", total.lapse, "\n\n\n"))
Gael  MILLOT's avatar
Gael MILLOT committed
2139
}
Gael  MILLOT's avatar
Gael MILLOT committed
2140

Gael  MILLOT's avatar
Gael MILLOT committed
2141

Gael  MILLOT's avatar
Gael MILLOT committed
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
################ Object modification


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


# Check OK: clear to go Apollo
fun_name_change <- function(data1, data2, added.string = "_modif"){
# 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
2158
# $data: the modified data1 (in the same order as in the initial data1)
Gael  MILLOT's avatar
Gael MILLOT committed
2159
2160
# $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
Gael's avatar
tempo    
Gael committed
2161
2162
2163
2164
# REQUIRED PACKAGES
# none
# REQUIRED FUNCTIONS FROM CUTE_LITTLE_R_FUNCTION
# fun_check()
Gael  MILLOT's avatar
Gael MILLOT committed
2165
2166
2167
2168
2169
2170
# 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
2171
function.name <- paste0(as.list(match.call(expand.dots = FALSE))[[1]], "()")
Gael  MILLOT's avatar
Gael MILLOT committed
2172
2173
2174
# end function name
# required function checking
if(length(utils::find("fun_check", mode = "function")) == 0){
2175
2176
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 ==
Gael  MILLOT's avatar
Gael MILLOT committed
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
}
# 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$fun.name))
tempo <- fun_check(data = data1, class = "vector", mode = "character", fun.name = function.name) ; eval(ee)
tempo <- fun_check(data = data2, class = "vector", mode = "character", fun.name = function.name) ; eval(ee)
tempo <- fun_check(data = added.string, class = "vector", mode = "character", length = 1, fun.name = function.name) ; eval(ee)
if(any(arg.check) == TRUE){
stop(paste0("\n\n================\n\n", paste(text.check[arg.check], collapse = "\n"), "\n\n================\n\n"), call. = FALSE) #
}
# source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.2/r_debugging_tools-v1.2.R") ; eval(parse(text = str_basic_arg_check_dev)) ; eval(parse(text = str_arg_check_with_fun_check_dev)) # activate this line and use the function (with no arguments left as NULL) to check arguments status and if they have been checked using fun_check()
# end argument checking
# main code
ini <- NULL
post <- NULL
if(any(data1 %in% data2)){
tempo.names <- data1[data1 %in% data2]
ini <- NULL
post <- NULL
2199
for(i2 in 1:length(tempo.names)){
Gael  MILLOT's avatar
Gael MILLOT committed
2200
count <- 0
2201
tempo <- tempo.names[i2]
Gael  MILLOT's avatar
Gael MILLOT committed
2202
2203
while(any(tempo %in% data2) | any(tempo %in% data1)){
count <- count + 1
2204
tempo <- paste0(tempo.names[i2], "_modif", count)
Gael  MILLOT's avatar
Gael MILLOT committed
2205
}
2206
data1[data1 %in% tempo.names[i2]] <- paste0(tempo.names[i2], "_modif", count)
Gael  MILLOT's avatar
Gael MILLOT committed
2207
if(count != 0){
2208
2209
ini <- c(ini, tempo.names[i2])
post <- c(post, paste0(tempo.names[i2], "_modif", count))
Gael  MILLOT's avatar
Gael MILLOT committed
2210
2211
2212
2213
2214
2215
2216
2217
}
}
data <- data1
}else{
data <- data1
}
output <- list(data = data, ini = ini, post = post)
return(output)
Gael  MILLOT's avatar
Gael MILLOT committed
2218
2219
2220
}


Gael  MILLOT's avatar
Gael MILLOT committed
2221
######## fun_df_remod() #### remodeling a data frame to have column name as a qualitative values and vice-versa
Gael  MILLOT's avatar
Gael MILLOT committed
2222
2223


Gael  MILLOT's avatar
Gael MILLOT committed
2224
# Check OK: clear to go Apollo
Gael's avatar
tempo    
Gael committed
2225
2226
2227
2228
2229
fun_df_remod <- function(
data, 
quanti.col.name = "quanti", 
quali.col.name = "quali"
){
Gael  MILLOT's avatar
Gael MILLOT committed
2230
2231
# 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
Gael  MILLOT's avatar
Gael MILLOT committed
2232

Gael  MILLOT's avatar
Gael MILLOT committed
2233
2234
 
# 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
Gael  MILLOT's avatar
Gael MILLOT committed
2235

Gael  MILLOT's avatar
Gael MILLOT committed
2236
2237
2238
2239
2240
2241
2242
2243
 

# 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
Gael's avatar
tempo    
Gael committed
2244
2245
2246
2247
# REQUIRED PACKAGES
# none
# REQUIRED FUNCTIONS FROM CUTE_LITTLE_R_FUNCTION
# fun_check()
Gael  MILLOT's avatar
Gael MILLOT committed
2248
# EXAMPLES
2249
2250
2251
# 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")
Gael  MILLOT's avatar
Gael MILLOT committed
2252
# DEBUGGING
2253
2254
2255
2256
2257
2258
# 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
Gael  MILLOT's avatar
Gael MILLOT committed
2259
# function name
2260
function.name <- paste0(as.list(match.call(expand.dots = FALSE))[[1]], "()")
Gael  MILLOT's avatar
Gael MILLOT committed
2261
2262
2263
# end function name
# required function checking
if(length(utils::find("fun_check", mode = "function")) == 0){
2264
2265
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 ==
Gael  MILLOT's avatar
Gael MILLOT committed
2266
2267
2268
2269
2270
}
# end required function checking
# argument checking
# argument checking without fun_check()
if( ! any(class(data) %in% "data.frame")){
2271
2272
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 ==
Gael  MILLOT's avatar
Gael MILLOT committed
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
}
# 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$fun.name))
tempo <- fun_check(data = quanti.col.name, class = "character", length = 1, fun.name = function.name) ; eval(ee)
tempo <- fun_check(data = quali.col.name, class = "character", length = 1, fun.name = function.name) ; eval(ee)
if(any(arg.check) == TRUE){
stop(paste0("\n\n================\n\n", paste(text.check[arg.check], collapse = "\n"), "\n\n================\n\n"), call. = FALSE) #
}
# end argument checking with fun_check()
# source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.2/r_debugging_tools-v1.2.R") ; eval(parse(text = str_basic_arg_check_dev)) ; eval(parse(text = str_arg_check_with_fun_check_dev)) # activate this line and use the function (with no arguments left as NULL) to check arguments status and if they have been checked using fun_check()
# end argument checking
# main code
tempo.factor <- unlist(lapply(data, class))
for(i in 1:length(tempo.factor)){ # convert factor columns as character
if(all(tempo.factor[i] == "factor")){
data[, i] <- as.character(data[, i])
}
}
tempo.factor <- unlist(lapply(data, mode))
if(length(data) == 2){
if( ! ((mode(data[, 1]) == "character" & mode(data[, 2]) == "numeric") | mode(data[, 2]) == "character" & mode(data[, 1]) == "numeric" | mode(data[, 2]) == "numeric" & mode(data[, 1]) == "numeric") ){
2298
2299
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 ==
Gael  MILLOT's avatar
Gael MILLOT committed
2300
2301
}
if((mode(data[, 1]) == "character" | mode(data[, 2]) == "character") & (quanti.col.name != "quanti" | quali.col.name != "quali")){
2302
2303
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 ==
Gael  MILLOT's avatar
Gael MILLOT committed
2304
2305
2306
}
}else{
if( ! all(tempo.factor %in% "numeric")){
2307
2308
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 ==
Gael  MILLOT's avatar
Gael MILLOT committed
2309
2310
2311
}
}
if(( ! any(tempo.factor %in% "character")) & is.null(names(data))){
2312
2313
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 ==
Gael  MILLOT's avatar
Gael MILLOT committed
2314
2315
2316
2317
2318
2319
2320
}
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))
2321
output.data <- data.frame(quanti, quali, stringsAsFactors = TRUE)
Gael  MILLOT's avatar
Gael MILLOT committed
2322
2323
2324
2325
2326
2327
2328
2329
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))
2330
output.data <- cbind(output.data, ini_rowname, stringsAsFactors = TRUE)
Gael  MILLOT's avatar
Gael MILLOT committed
2331
2332
2333
}
}else{ # transfo 2
if(class(data[, 1]) == "character"){
2334
data <- cbind(data[2], data[1], stringsAsFactors = TRUE)
Gael  MILLOT's avatar
Gael MILLOT committed
2335
2336
2337
2338
2339
}
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
2340
output.data<-data.frame(tempo, stringsAsFactors = TRUE)
Gael  MILLOT's avatar
Gael MILLOT committed
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
}
return(output.data)
}




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


# Check OK: clear to go Apollo
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
Gael's avatar
tempo    
Gael committed
2365
2366
2367
2368
# REQUIRED PACKAGES
# none
# REQUIRED FUNCTIONS FROM CUTE_LITTLE_R_FUNCTION
# fun_check()
Gael  MILLOT's avatar
Gael MILLOT committed
2369
2370
2371
2372
2373
2374
2375
2376
2377
# 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
2378
function.name <- paste0(as.list(match.call(expand.dots = FALSE))[[1]], "()")
Gael  MILLOT's avatar
Gael MILLOT committed
2379
2380
2381
# end function name
# required function checking
if(length(utils::find("fun_check", mode = "function")) == 0){
2382
2383
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 ==
Gael  MILLOT's avatar
Gael MILLOT committed
2384
2385
2386
2387
2388
}
# end required function checking
# argument checking
# argument checking without fun_check()
if( ! (all(typeof(data) == "character") | all(typeof(data) == "double") | all(typeof(data) == "integer"))){
2389
2390
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 ==
Gael  MILLOT's avatar
Gael MILLOT committed
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
}
# 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$fun.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()
# source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.2/r_debugging_tools-v1.2.R") ; eval(parse(text = str_basic_arg_check_dev)) ; eval(parse(text = str_arg_check_with_fun_check_dev)) # activate this line and use the function (with no arguments left as NULL) to check arguments status and if they have been checked using fun_check()
# end argument checking
# main code
tempo <- grepl(x = data, pattern = "\\.") # detection of decimal numbers
ini.mode <- mode(data)
data <- as.character(data) # to really truncate decimal digits
for(i in 1:length(data)){ # scan all the numbers of the vector
if(tempo[i] == TRUE){ # means decimal number
if(after.lead.zero == TRUE){
zero.pos <- unlist(gregexpr(text=data[i], pattern = 0)) # recover all the position of the zeros in the number. -1 if no zeros (do not record the leading and trailing zeros)
}else{
zero.pos <- -1 # -1 as if no zero
}
dot.pos <- unlist(gregexpr(text=data[i], pattern = "\\.")) # recover all the position of the zeros in the number
digit.pos <- unlist(gregexpr(text=data[i], pattern = "[[:digit:]]")) # recover all the position of the digits in the number
dec.pos <- digit.pos[digit.pos > dot.pos]
count <- 0
while((dot.pos + count + 1) %in% zero.pos & (dot.pos + count + 1) <= max(dec.pos) & (count + dec.nb) < length(dec.pos)){ # count the number of leading zeros in the decimal part
count <- count + 1
}
data[i] <- formatC(as.numeric(data[i]), digits = (count + dec.nb), format = "f")
}
}
if(ini.mode != "character"){
data <- as.numeric(data)
}
return(data)
}


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


# Check OK: clear to go Apollo
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
Gael's avatar
tempo    
Gael committed
2447
2448
2449
2450
# REQUIRED PACKAGES
# none
# REQUIRED FUNCTIONS FROM CUTE_LITTLE_R_FUNCTION
# fun_check()
Gael  MILLOT's avatar
Gael MILLOT committed
2451
2452
2453
2454
2455
2456
# 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
2457
function.name <- paste0(as.list(match.call(expand.dots = FALSE))[[1]], "()")
Gael  MILLOT's avatar
Gael MILLOT committed
2458
2459
2460
# end function name
# required function checking
if(length(utils::find("fun_check", mode = "function")) == 0){
2461
2462
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 ==
Gael  MILLOT's avatar
Gael MILLOT committed
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
}
# 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$fun.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) #
}
# source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.2/r_debugging_tools-v1.2.R") ; eval(parse(text = str_basic_arg_check_dev)) ; eval(parse(text = str_arg_check_with_fun_check_dev)) # activate this line and use the function (with no arguments left as NULL) to check arguments status and if they have been checked using fun_check()
# end argument checking
# main code
for (i in 1:ncol(data)){data[,i] <- rev(data[,i])}
data <- t(data)
return(data)
}


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


# Check OK: clear to go Apollo
Gael's avatar
tempo    
Gael committed
2487
2488
2489
2490
2491
2492
2493
2494
fun_mat_num2color <- function(
mat1, 
mat.hsv.h = TRUE, 
notch = 1, 
s = 1, 
v = 1, 
forced.color = NULL
){
Gael  MILLOT's avatar
Gael MILLOT committed
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
# 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
Gael's avatar
tempo    
Gael committed
2510
2511
2512
2513
# REQUIRED PACKAGES
# none
# REQUIRED FUNCTIONS FROM CUTE_LITTLE_R_FUNCTION
# fun_check()
Gael  MILLOT's avatar
Gael MILLOT committed
2514
2515
2516
2517
2518
# 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
2519
function.name <- paste0(as.list(match.call(expand.dots = FALSE))[[1]], "()")
Gael  MILLOT's avatar
Gael MILLOT committed
2520
2521
2522
# end function name
# required function checking
if(length(utils::find("fun_check", mode = "function")) == 0){
2523
2524
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 ==
Gael  MILLOT's avatar
Gael MILLOT committed
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
}
# 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$fun.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()
Gael  MILLOT's avatar
Gael MILLOT committed
2543
if(mat.hsv.h == TRUE & fun_check(data = mat1, mode = "numeric", prop = TRUE)$problem == TRUE){
2544
2545
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 ==
Gael  MILLOT's avatar
Gael MILLOT committed
2546
2547
2548
2549
}
if( ! is.null(forced.color)){
tempo <- fun_check(data = forced.color, class = "character")
if(any(tempo$problem == TRUE)){
2550
2551
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 ==
Gael  MILLOT's avatar
Gael MILLOT committed
2552
2553
}
if( ! all(forced.color %in% colors() | grepl(pattern = "^#", forced.color))){ # check that all strings of forced.color start by #
2554
2555
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 ==
Gael  MILLOT's avatar
Gael MILLOT committed
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
}
}
# end argument checking without fun_check()
# source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.2/r_debugging_tools-v1.2.R") ; eval(parse(text = str_basic_arg_check_dev)) ; eval(parse(text = str_arg_check_with_fun_check_dev)) # activate this line and use the function (with no arguments left as NULL) to check arguments status and if they have been checked using fun_check()
# end argument checking
# main code
problem <- NULL
text.problem <- NULL
mat1.name <- deparse(substitute(mat1))
# change the scale of the plotted matrix
if(mat.hsv.h == TRUE){
if(any(min(mat1, na.rm = TRUE) < 0 | max(mat1, na.rm = TRUE) > 1, na.rm = TRUE)){
2568
2569
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 ==
Gael  MILLOT's avatar
Gael MILLOT committed
2570
2571
2572
}
}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
2573
2574
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 ==
Gael  MILLOT's avatar
Gael MILLOT committed
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
}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)){
2585
2586
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 ==
Gael  MILLOT's avatar
Gael MILLOT committed
2587
}else if(length(different.color) != length(tempo.different.color)){
2588
2589
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 ==
Gael  MILLOT's avatar
Gael MILLOT committed
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
}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
2609
2610
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 ==
Gael  MILLOT's avatar
Gael MILLOT committed
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
}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


# Check OK: clear to go Apollo
fun_mat_op <- function(mat.list, kind.of.operation = "+"){
# AIM
# assemble several matrices of same dimensions by performing by case operation. For instance add the value of all the case 1 (row1 & column1) of the matrices and put it in the case 1 of a new matrix M, add the value of all the case 2 (row2 & column1) of the matrices and put it in the case 2 of a new matrix M, etc.
 
# c: case
# i: row number
# j: column number
# k: matrix number
# z: number of matrices
# 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
Gael's avatar
tempo    
Gael committed
2639
2640
2641
2642
2643
# REQUIRED PACKAGES
# none
# REQUIRED FUNCTIONS FROM CUTE_LITTLE_R_FUNCTION
# fun_check()
# fun_comp_2d()
Gael  MILLOT's avatar
Gael MILLOT committed
2644
2645
2646
2647
2648
2649
2650
2651
2652
# EXAMPLES
# mat1 = matrix(c(1,1,1,2,1,5,9,8), ncol = 2) ; mat2 = matrix(c(1,1,1,2,1,5,9,NA), ncol = 2) ; fun_mat_op(mat.list = list(mat1, mat2), kind.of.operation = "+")
# mat1 = matrix(c(1,1,1,2,1,5,9,8), ncol = 2, dimnames = list(LETTERS[1:4], letters[1:2])) ; mat2 = matrix(c(1,1,1,2,1,5,9,NA), ncol = 2, dimnames = list(LETTERS[1:4], letters[1:2])) ; fun_mat_op(mat.list = list(mat1, mat2), kind.of.operation = "*")
# mat1 = matrix(c(1,1,1,2,1,5,9,8), ncol = 2, dimnames = list(LETTERS[1:4], c(NA, NA))) ; mat2 = matrix(c(1,1,1,2,1,5,9,NA), ncol = 2, dimnames = list(LETTERS[1:4], letters[1:2])) ; fun_mat_op(mat.list = list(mat1, mat2), kind.of.operation = "-")
# mat1 = matrix(c(1,1,1,2,1,5,9,8), ncol = 2, dimnames = list(c("A1", "A2", "A3", "A4"), letters[1:2])) ; mat2 = matrix(c(1,1,1,2,1,5,9,NA), ncol = 2, dimnames = list(LETTERS[1:4], letters[1:2])) ; mat3 = matrix(c(1,1,1,2,1,5,9,NA), ncol = 2, dimnames = list(LETTERS[1:4], letters[1:2])) ; fun_mat_op(mat.list = list(mat1, mat2, mat3), kind.of.operation = "+")
# DEBUGGING
# mat1 = matrix(c(1,1,1,2,1,5,9,8), ncol = 2) ; mat2 = matrix(c(1,1,1,2,1,5,9,NA), ncol = 2) ; mat.list = list(mat1, mat2) ; kind.of.operation = "+" # for function debugging
# mat1 = matrix(c(1,1,1,2,1,5,9,8), ncol = 2, dimnames = list(LETTERS[1:4], c(NA, NA))) ; mat2 = matrix(c(1,1,1,2,1,5,9,NA), ncol = 2, dimnames = list(LETTERS[1:4], letters[1:2])) ; mat.list = list(mat1, mat2) ; kind.of.operation = "*" # for function debugging
# function name
2653
function.name <- paste0(as.list(match.call(expand.dots = FALSE))[[1]], "()")
Gael  MILLOT's avatar
Gael MILLOT committed
2654
2655
2656
# end function name
# required function checking
if(length(utils::find("fun_check", mode = "function")) == 0){
2657
2658
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 ==
Gael  MILLOT's avatar
Gael MILLOT committed
2659
2660
}
if(length(utils::find("fun_check", mode = "function")) == 0){
2661
2662
tempo.cat <- paste0("ERROR IN ", function.name, ": REQUIRED fun_comp_2d() 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 ==
Gael  MILLOT's avatar
Gael MILLOT committed
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
}
# 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$fun.name))
tempo <- fun_check(data = mat.list, class = "list", fun.name = function.name) ; eval(ee)
tempo <- fun_check(data = kind.of.operation, options = c("+", "-", "*"), length = 1, fun.name = function.name) ; eval(ee)
if(any(arg.check) == TRUE){
stop(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(length(mat.list) < 2){
2679
2680
tempo.cat <- paste0("ERROR IN ", function.name, ": mat.list ARGUMENT MUST BE A LIST CONTAINING AT LEAST 2 MATRICES")
stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
Gael  MILLOT's avatar
Gael MILLOT committed
2681
}
2682
2683
for(i1 in 1:length(mat.list)){
tempo <- fun_check(data = mat.list[[i1]], class = "matrix", mode = "numeric", na.contain = TRUE)
Gael  MILLOT's avatar
Gael MILLOT committed
2684
if(tempo$problem == TRUE){
2685
2686
tempo.cat <- paste0("ERROR IN ", function.name, ": ELEMENT ", i1, " OF mat.list ARGUMENT MUST BE A NUMERIC MATRIX")
stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
Gael  MILLOT's avatar
Gael MILLOT committed
2687
2688
2689
2690
}
}
ident.row.names <- TRUE
ident.col.names <- TRUE
2691
2692
for(i1 in 2:length(mat.list)){
tempo <- fun_comp_2d(data1 = mat.list[[1]], data2 = mat.list[[i1]])
Gael  MILLOT's avatar
Gael MILLOT committed
2693
if(tempo$same.dim == FALSE){
2694
2695
tempo.cat <- paste0("ERROR IN ", function.name, ": MATRIX ", i1, " OF mat.list ARGUMENT MUST HAVE THE SAME DIMENSION (", paste(dim(mat.list[[i1]]), collapse = " "), ") THAN THE MATRIX 1 IN mat.list (", paste(dim(mat.list[[1]]), 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 ==
Gael  MILLOT's avatar
Gael MILLOT committed
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
}
if( ! is.null(tempo$same.row.name)){
if(tempo$same.row.name != TRUE){ # != TRUE to deal with NA
ident.row.names <- FALSE
}
}
if( ! is.null(tempo$same.col.name)){
if(tempo$same.col.name != TRUE){ # != TRUE to deal with NA
ident.col.names <- FALSE
}
}
}
# end argument checking without fun_check()
# source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.2/r_debugging_tools-v1.2.R") ; eval(parse(text = str_basic_arg_check_dev)) ; eval(parse(text = str_arg_check_with_fun_check_dev)) # activate this line and use the function (with no arguments left as NULL) to check arguments status and if they have been checked using fun_check()
# end argument checking
# main code
output <- mat.list[[1]]
2713
for(i1 in 2:length(mat.list)){
2714
output <- get(kind.of.operation)(output, mat.list[[i1]]) # no env = sys.nframe(), inherit = FALSE in get() because look for function in the classical scope
Gael  MILLOT's avatar
Gael MILLOT committed
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
}
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)
}


######## 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
# ARGUMENTS:
# mat: a square numeric matrix without NULL, NA, Inf or single case (dimension 1, 1) of 0
# RETURN
# the inversed matrix
Gael's avatar
tempo    
Gael committed
2738
2739
2740
2741
# REQUIRED PACKAGES
# none
# REQUIRED FUNCTIONS FROM CUTE_LITTLE_R_FUNCTION
# fun_check()
Gael  MILLOT's avatar
Gael MILLOT committed
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
# EXAMPLES
# mat1 = matrix(c(1,1,1,2,1,5,9,8,9), ncol = 3) ; fun_mat_inv(mat = mat1) # use solve()
# mat1 = matrix(c(0,0,0,0,0,0,0,0,0), ncol = 3) ; fun_mat_inv(mat = mat1) # use the trick
# mat1 = matrix(c(1,1,1,2,Inf,5,9,8,9), ncol = 3) ; fun_mat_inv(mat = mat1)
# mat1 = matrix(c(1,1,1,2,NA,5,9,8,9), ncol = 3) ; fun_mat_inv(mat = mat1)
# mat1 = matrix(c(1,2), ncol = 1) ; fun_mat_inv(mat = mat1)
# mat1 = matrix(0, ncol = 1) ; fun_mat_inv(mat = mat1)
# mat1 = matrix(2, ncol = 1) ; fun_mat_inv(mat = mat1)
# DEBUGGING
# mat = matrix(c(1,1,1,2,1,5,9,8,9), ncol = 3) # for function debugging
# function name
2753
function.name <- paste0(as.list(match.call(expand.dots = FALSE))[[1]], "()")
Gael  MILLOT's avatar
Gael MILLOT committed
2754
2755
2756
# end function name
# required function checking
if(length(utils::find("fun_check", mode = "function")) == 0){
2757
2758
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 ==
Gael  MILLOT's avatar
Gael MILLOT committed
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
}
# 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$fun.name))
tempo <- fun_check(data = mat, class = "matrix", mode = "numeric", 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(ncol(mat) != nrow(mat)){
2774
2775
tempo.cat <- paste0("ERROR IN ", function.name, ": mat ARGUMENT MUST BE A SQUARE MATRIX")
stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
Gael  MILLOT's avatar
Gael MILLOT committed
2776
2777
}
if(any(mat %in% c(Inf, -Inf, NA))){
2778
2779
tempo.cat <- paste0("ERROR IN ", function.name, ": mat ARGUMENT MUST BE A MATRIX WITHOUT Inf, -Inf OR NA")
stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
Gael  MILLOT's avatar
Gael MILLOT committed
2780
2781
}
if(all(mat == 0) & ncol(mat) == 1){
2782
2783
tempo.cat <- paste0("ERROR IN ", function.name, ": mat ARGUMENT CANNOT BE A SQUARE MATRIX MADE OF A SINGLE CASE OF 0")
stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
Gael  MILLOT's avatar
Gael MILLOT committed
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
}
# end argument checking without fun_check()
# source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.2/r_debugging_tools-v1.2.R") ; eval(parse(text = str_basic_arg_check_dev)) ; eval(parse(text = str_arg_check_with_fun_check_dev)) # activate this line and use the function (with no arguments left as NULL) to check arguments status and if they have been checked using fun_check()
# end argument checking
# main code
if(any(grepl(x = try(solve(mat), silent = TRUE)[], pattern = "[Ee]rror"))){
tempo <- svd(mat)
val.critique <- which(tempo$d < 10^-8)
Diag.mod <- diag(1 / tempo$d)
for(i in val.critique){
Diag.mod[i, i] <- 0
}
return(tempo$v %*% Diag.mod %*% t(tempo$u))
}else{
return(solve(mat))
}
}


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


# Check OK: clear to go Apollo
fun_mat_fill <- function(mat, empty.cell.string = 0, warn.print = FALSE){
# AIM
# detect the empty half part of a symmetric square matrix (either topleft, topright, bottomleft or bottomright)
# fill this empty half part using the other symmetric half part of the matrix
# WARNINGS
# a plot verification using fun_gg_heatmap() is recommanded
# ARGUMENTS:
# mat: a numeric or character square matrix with the half part (according to the grand diagonal) filled with NA (any kind of matrix), "0" (character matrix) or 0 (numeric matrix) exclusively (not a mix of 0 and NA in the empty part)
# empty.cell.string: a numeric, character or NA (no quotes) indicating what empty cells are filled with
# warn.print: logical. Print warnings at the end of the execution? No print if no warning messages
# RETURN
# a list containing:
# $mat: the filled matrix
# $warn: the warning messages. Use cat() for proper display. NULL if no warning
Gael's avatar
tempo    
Gael committed
2821
2822
2823
2824
# REQUIRED PACKAGES
# none
# REQUIRED FUNCTIONS FROM CUTE_LITTLE_R_FUNCTION
# fun_check()
Gael  MILLOT's avatar
Gael MILLOT committed
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
# EXAMPLES
# mat1 = matrix(c(1,NA,NA,NA, 0,2,NA,NA, NA,3,4,NA, 5,6,7,8), ncol = 4) ; mat1 ; fun_mat_fill(mat = mat1, empty.cell.string = NA, warn.print = TRUE) # bottomleft example
# mat1 = matrix(c(1,1,1,2, 0,2,3,0, NA,3,0,0, 5,0,0,0), ncol = 4) ; mat1 ; fun_mat_fill(mat = mat1, empty.cell.string = NA, warn.print = TRUE) # error example
# mat1 = matrix(c(1,1,1,2, 0,2,3,0, NA,3,0,0, 5,0,0,0), ncol = 4) ; mat1 ; fun_mat_fill(mat = mat1, empty.cell.string = 0, warn.print = TRUE) # bottomright example
# mat1 = matrix(c(1,1,1,2, "a",2,3,NA, "a","a",0,0, "a","a","a",0), ncol = 4) ; mat1 ; fun_mat_fill(mat = mat1, empty.cell.string = "a", warn.print = TRUE) # topright example
# mat1 = matrix(c(0,0,0,2, 0,0,3,0, 0,3,0,NA, 5,0,0,0), ncol = 4) ; mat1 ; fun_mat_fill(mat = mat1, empty.cell.string = 0, warn.print = TRUE) # topleft example
# mat1 = matrix(c(0,0,0,2, 0,0,3,0, 0,3,0,0, 5,0,0,0), ncol = 4) ; mat1 ; fun_mat_fill(mat = mat1, empty.cell.string = 0, warn.print = TRUE) # error example
# DEBUGGING
# mat = matrix(c(1,NA,NA,NA, 0,2,NA,NA, NA,3,4,NA, 5,6,7,8), ncol = 4) ; empty.cell.string = NA ; warn.print = TRUE # for function debugging
# mat = matrix(c(0,0,0,2, 0,0,3,0, 0,3,0,NA, 5,0,0,0), ncol = 4) ; empty.cell.string = 0 ; warn.print = TRUE # for function debugging # topleft example
# mat = matrix(c(0,0,0,2, 0,0,3,0, 0,3,0,NA, 5,0,0,0), ncol = 4) ; empty.cell.string = NA ; warn.print = TRUE # for function debugging # topleft example
# function name
2837
function.name <- paste0(as.list(match.call(expand.dots = FALSE))[[1]], "()")
Gael  MILLOT's avatar
Gael MILLOT committed
2838
2839
2840
# end function name
# required function checking
if(length(utils::find("fun_check", mode = "function")) == 0){
2841
2842
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 ==
Gael  MILLOT's avatar
Gael MILLOT committed
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
}
# 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$fun.name))
tempo <- fun_check(data = mat, class = "matrix", na.contain = TRUE, fun.name = function.name) ; eval(ee)
tempo <- fun_check(data = empty.cell.string, class = "vector", na.contain = TRUE, fun.name = function.name) ; eval(ee)
tempo <- fun_check(data = warn.print, class = "logical", length = 1, fun.name = function.name) ; eval(ee)
if(any(arg.check) == TRUE){
stop(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(ncol(mat) != nrow(mat)){
2860
2861
tempo.cat <- paste0("ERROR IN ", function.name, ": mat ARGUMENT MUST BE A SQUARE MATRIX")
stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
Gael  MILLOT's avatar
Gael MILLOT committed
2862
2863
}
if( ! (mode(mat) %in% c("numeric", "character"))){
2864
2865
tempo.cat <- paste0("ERROR IN ", function.name, ": mat ARGUMENT MUST BE A NUMERIC OR CHARACTER MATRIX")
stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
Gael  MILLOT's avatar
Gael MILLOT committed
2866
2867
}
if(nrow(mat) == 1 & ncol(mat) == 1){
2868
2869
tempo.cat <- paste0("ERROR IN ", function.name, ": mat ARGUMENT CANNOT BE A SQUARE MATRIX MADE OF A SINGLE CASE")
stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
Gael  MILLOT's avatar
Gael MILLOT committed
2870
2871
}
if(ifelse(is.na(empty.cell.string), ! any(is.na(mat)), ! any(mat == empty.cell.string, na.rm = TRUE))){
2872
2873
tempo.cat <- paste0("ERROR IN ", function.name, ": mat ARGUMENT MATRIX MUST HAVE CELLS WITH THE EMPTY STRING SPECIFIED IN empty.cell.string ARGUMENT")
stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n"), call. = FALSE) # == in stop() to be able to add several messages between ==
Gael  MILLOT's avatar
Gael MILLOT committed
2874
2875
2876
2877
2878
2879
}
# end argument checking without fun_check()
# source("C:/Users/Gael/Documents/Git_versions_to_use/debugging_tools_for_r_dev-v1.2/r_debugging_tools-v1.2.R") ; eval(parse(text = str_basic_arg_check_dev)) ; eval(parse(text = str_arg_check_with_fun_check_dev)) # activate this line and use the function (with no arguments left as NULL) to check arguments status and if they have been checked using fun_check()
# end argument checking
# main code
list.diag <- vector("list", length = nrow(mat) - 1)
2880
2881
for(i1 in 1:(nrow(mat) - 1)){
list.diag[[i1]] <- numeric(length = nrow(mat) - i1)
Gael  MILLOT's avatar
Gael MILLOT committed
2882
2883
2884
}
sector <- c("topleft", "topright", "bottomright", "bottomleft")
diag.scan <-c( # same order as sector. Recover each diag from center to corner
2885
2886
2887
2888
"mat[as.matrix(as.data.frame(list(1:(nrow(mat) - i2), (ncol(mat) -i2):1), stringsAsFactors = TRUE))]", # topleft part
"mat[as.matrix(as.data.frame(list(1:(nrow(mat) - i2), (1:ncol(mat))[-(1:i2)]), stringsAsFactors = TRUE))]", # topright part
"mat[as.matrix(as.data.frame(list((1 + i2):nrow(mat), ncol(mat):(1 + i2)), stringsAsFactors = TRUE))]", # bottomright part
"mat[as.matrix(as.data.frame(list((1 + i2):nrow(mat), 1:(ncol(mat) -i2)), stringsAsFactors = TRUE))]" # bottomleft part
Gael  MILLOT's avatar
Gael MILLOT committed
2889
2890
2891
2892
2893
)
# empty part detection
tempo.list.diag <- list.diag
empty.sector <- NULL
full.sector <- NULL
2894
2895
2896
ini.warning.length <- options()$warning.length
options(warning.length = 8170)
on.exit(exp = options(warning.length = ini.warning.length))
Gael  MILLOT's avatar
Gael MILLOT committed
2897
warn <- NULL
Gael  MILLOT's avatar
Gael MILLOT committed
2898
warn.count <- 0
2899
for(i1 in 1:length(sector)){
Gael  MILLOT's avatar
Gael MILLOT committed
2900
tempo.list.diag <- list.diag
2901
2902
2903
2904
for(i2 in 1:(nrow(mat) - 1)){
tempo.list.diag[[i2]] <- eval(parse(text = diag.scan[i1]))
if(ifelse(is.na(empty.cell.string), ! all(is.na(tempo.list.diag[[i2]])), ! (all(tempo.list.diag[[i2]] == empty.cell.string, na.rm = TRUE) & ! (is.na(all(tempo.list.diag[[i2]] == empty.cell.string, na.rm = FALSE)))))){ # I had to add this ! (is.na(all(tempo.list.diag[[i2]] == empty.cell.string, na.rm = FALSE))) because all(tempo.list.diag[[i2]] == empty.cell.string, na.rm = FALSE) gives NA and not FALSE if one NA in tempo.list.diag[[i2]] -> not good for if()
full.sector <- c(full.sector, sector[i1])
Gael  MILLOT's avatar
Gael MILLOT committed
2905
2906
2907
2908
2909
break
}
}
if(i1 == nrow(mat) - 1){
if(all(unlist(lapply(tempo.list.diag, FUN = function(x){if(is.na(empty.cell.string)){is.na(x)}else{x == empty.cell.string}})), na.rm = TRUE)){
2910
empty.sector <- c(empty.sector, sector[i1])
Gael  MILLOT's avatar
Gael MILLOT committed
2911
warn.count <- warn.count + 1
2912
tempo.warn <- paste0("(", warn.count,") EMPTY SECTOR DETECTED ON THE ", toupper(sector[i1]), " CORNER, FULL OF ", empty.cell.string)
Gael  MILLOT's avatar
Gael MILLOT committed
2913
2914
warn <- paste0(ifelse(is.null(warn), tempo.warn, paste0(warn, "\n\n", tempo.warn)))
}else{
2915
2916
tempo.cat <- paste0("ERROR IN ", function.name, ": THE ", toupper(sector[i1]), " SECTOR, DETECTED AS EMPTY, IS NOT? DIFFERENT VALUES IN THIS SECTOR:\n", paste(names(table(unlist(tempo.list.diag), useNA = "ifany")), collapse = " "))
stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n", ifelse(is.null(warn), "", paste0("IN ADDITION\nWARNING", ifelse(warn.count > 1, "S", ""), ":\n\n", warn))), call. = FALSE) # == in stop() to be able to add several messages between ==
Gael  MILLOT's avatar
Gael MILLOT committed
2917
2918
2919
2920
2921
}
}
}
# end empty part detection
if(length(empty.sector) == 0){
Gael  MILLOT's avatar
Gael MILLOT committed
2922
warn.count <- warn.count + 1
2923
tempo.warn <- paste0("(", warn.count,") ACCORDING TO empty.cell.string ARGUMENT (", empty.cell.string, "), mat ARGUMENT MATRIX HAS ZERO EMPTY HALF PART")
Gael  MILLOT's avatar
Gael MILLOT committed
2924
2925
2926
warn <- paste0(ifelse(is.null(warn), tempo.warn, paste0(warn, "\n\n", tempo.warn)))
}else{
if(length(empty.sector) > 1){
2927
2928
tempo.cat <- paste0("ERROR IN ", function.name, ": ACCORDING TO empty.cell.string ARGUMENT (", empty.cell.string, "), mat ARGUMENT MATRIX HAS MORE THAN ONE EMPTY HALF PART (ACCORDING TO THE GRAND DIAGONAL): ", paste(empty.sector, collapse = " "))
stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n", ifelse(is.null(warn), "", paste0("IN ADDITION\nWARNING", ifelse(warn.count > 1, "S", ""), ":\n\n", warn))), call. = FALSE) # == in stop() to be able to add several messages between ==
Gael  MILLOT's avatar
Gael MILLOT committed
2929
}else if(any(full.sector %in% empty.sector, na.rm = TRUE)){
2930
2931
tempo.cat <- paste0("ERROR IN ", function.name, ": THE FUNCTION HAS DETECTED EMPTY AND NON EMPTY HALF PART IN THE SAME SECTOR: ", paste(full.sector[full.sector %in% empty.sector], collapse = " "))
stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n", ifelse(is.null(warn), "", paste0("IN ADDITION\nWARNING", ifelse(warn.count > 1, "S", ""), ":\n\n", warn))), call. = FALSE) # == in stop() to be able to add several messages between ==
Gael  MILLOT's avatar
Gael MILLOT committed
2932
}else if(length(empty.sector) + length(full.sector)!= 4){
2933
2934
tempo.cat <- paste0("ERROR IN ", function.name, ": THE FUNCTION HAS DETECTED MORE OR LESS SECTORS THAN 4:\nHALF SECTORS:", paste(empty.sector, collapse = " "), "\nFULL SECTORS:", paste(full.sector, collapse = " "))
stop(paste0("\n\n================\n\n", tempo.cat, "\n\n================\n\n", ifelse(is.null(warn), "", paste0("IN ADDITION\nWARNING", ifelse(warn.count > 1, "S", ""), ":\n\n", warn))), call. = FALSE) # == in stop() to be able to add several messages between ==
Gael  MILLOT's avatar
Gael MILLOT committed
2935
}else{
Gael  MILLOT's avatar
Gael MILLOT committed
2936
warn.count <- warn.count + 1
2937
tempo.warn <- paste0("(", warn.count,") ", toupper(empty.sector), " SECTOR HAS BEEN COMPLETED TO BECOME SYMMETRICAL")
Gael  MILLOT's avatar
Gael MILLOT committed
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
warn <- paste0(ifelse(is.null(warn), tempo.warn, paste0(warn, "\n\n", tempo.warn)))
}
# matrix filling
for(i1 in 1:(nrow(mat) - 1)){
if(empty.sector == "topleft"){
eval(parse(text = paste0(diag.scan[1], " <- ", diag.scan[3])))
}else if(empty.sector == "topright"){
eval(parse(text = paste0(diag.scan[2], " <- ", diag.scan[4])))
}else if(empty.sector == "bottomright"){
eval(parse(text = paste0(diag.scan[3], " <- ", diag.scan[1])))
}else if(empty.sector == "bottomleft"){
eval(parse(text = paste0(diag.scan[4], " <- ", diag.scan[2])))
}
}
# end matrix filling
}
if(warn.print == TRUE & ! is.null(warn)){
2955
warning(paste0("FROM ", function.name, ":\n\n", warn), call. = FALSE)
Gael  MILLOT's avatar
Gael MILLOT committed
2956
2957
2958
2959
2960
2961
2962
2963
}
return(list(mat = mat, warn = warn))
}


######## fun_permut() #### progressively breaks a vector order


Gael's avatar
tempo    
Gael committed
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
fun_permut <- function(
data1, 
data2 = NULL, 
n = NULL, 
seed = NULL, 
print.count = 10, 
text.print = "", 
cor.method = "spearman", 
cor.limit = 0.2, 
warn.print = FALSE, 
lib.path = NULL
){
Gael  MILLOT's avatar
Gael MILLOT committed
2976
2977
2978
2979
2980
# AIM
# reorder the elements of the data1 vector by flipping 2 randomly selected  consecutive positions either:
# 1) n times (when n is precised) or
# 2) until the correlation between data1 and data2 decreases down to the cor.limit (0.2 by default). See cor.limit below to deal with negative correlations
# Example of consecutive position flipping: ABCD -> BACD -> BADC, etc.
Gael's avatar
Gael committed
2981
# designed for discrete values, but worls also for continuous values
Gael  MILLOT's avatar
Gael MILLOT committed
2982
2983
# WARNINGS
# see # https://www.r-bloggers.com/strategies-to-speedup-r-code/ for code speedup
Gael's avatar
Gael committed
2984
# the random switch of non consecutive positions (ABCD -> DBCA for instance) does not work very well as the correlation is quickly obtained but the initial vector structure is mainly kept (no much order). Ths code would be: pos <- ini.pos[1:2] ; pos <- sample.int(n = n , size = 2, replace = FALSE) ; tempo.pos[pos] <- tempo.pos[rev(pos)]
Gael  MILLOT's avatar
Gael MILLOT committed
2985
2986
2987
2988
2989
# ARGUMENTS
# data1: a vector of at least 2 elements. Must be numeric if data2 is specified
# data2: a numeric vector of same length as data1
# n: number of times "flipping 2 randomly selected consecutive positions". Ignored if data2 is specified
# seed: integer number used by set.seed(). Write NULL if random result is required, an integer otherwise. BEWARE: if not NULL, fun_permut() will systematically return the same result when the other parameters keep the same settings
Gael  MILLOT's avatar
Gael MILLOT committed
2990
2991
# print.count: interger value. Print a working progress message every print.count during loops. BEWARE: can increase substentially the time to complete the process using a small value, like 10 for instance. Use Inf is no loop message desired
# text.print: optional message to add to the working progress message every print.count loop
Gael  MILLOT's avatar
Gael MILLOT committed
2992
2993
2994
# cor.method: correlation method. Either "pearson", "kendall" or "spearman". Ignored if data2 is not specified
# cor.limit: a correlation limit (between 0 and 1). Ignored if data2 is not specified. Compute the correlation between data1 and data2, permute the data1 values, and stop the permutation process when the correlation between data1 and data2 decreases down below the cor limit value (0.2 by default). If cor(data1, data2) is negative, then -cor.limit is used and the process stops until the correlation between data1 and data2 increases up over cor.limit (-0.2 by default). BEWARE: write a positive cor.limit even if cor(data1, data2) is known to be negative. The function will automatically uses -cor.limit. If the initial correlation is already below cor.limit (positive correlation) or over -cor.limit (negative correlation), then the data1 value positions are completely randomized (correlation between data1 and data2 is expected to be 0)
# warn.print: logical. Print warnings at the end of the execution? No print if no warning messages
2995
# lib.path: character vector specifying the absolute pathways of the directories containing the required packages if not in the default directories. Ignored if NULL
Gael  MILLOT's avatar
Gael MILLOT committed
2996
2997
2998
2999
3000
# RETURN
# a list containing:
# $data: the modified vector
# $warn: potential warning messages (in case of negative correlation when data2 is specified). NULL if non warning message
# $cor: a spearman correlation between the initial positions (1:length(data1) and the final positions if data2 is not specified and the final correlation between data1 and data2 otherwise, according to cor.method