-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCodeAndRoll.R
More file actions
1839 lines (1475 loc) · 86.2 KB
/
CodeAndRoll.R
File metadata and controls
1839 lines (1475 loc) · 86.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
######################################################################
# A collection of custom R functions
######################################################################
# source('~/GitHub/Packages/CodeAndRoll/CodeAndRoll.R')
# source('https://raw.githubusercontent.com/vertesy/CodeAndRoll/master/CodeAndRoll.R')
## If something is not found:
# try(source("https://raw.githubusercontent.com/vertesy/ggExpressDev/main/ggExpress.functions.R"), silent = T)
# try(source("~/Github/TheCorvinas/R/RNA_seq_specific_functions.r"), silent = T)
## For Plotting From Clipboard or Files
# source("~/Github/TheCorvinas/R/Plotting.From.Clipboard.And.Files.r")
# # Load sequence length and base distribution check
# source("~/Github/TheCorvinas/R/Gene.Stats.mm10.R")
suppressMessages(try(require(clipr), silent = T))
try(require(ggplot2),silent = T)
### CHAPTERS:
# - Generic functions
# - File handling, export, import [read & write]
# - Clipboard interaction (OS X)
# - Reading files in
# - Writing files out
# - Create and check variables
# - Vector operations
# - Vector filtering
# - String operations
# - Matrix operations
# - Matrix filtering
# - List operations
# - Set operations
# - Math and stats
# - Plotting and Graphics
# - Clustering heatmap tools
# - Search query links
# - Biology
# - Generic
# - New additions
wA4 = 8.27 # A4 inches
hA4 = 11.69
## Setup -------------------------------------------------------------------------------------------------
# pdf.options(title = paste0('Copyright Abel Vertesy ', Sys.Date())) # Setup to your own name
debuggingState(on = FALSE)
# "gtools", "readr", "gdata", "colorRamps", "grDevices", "plyr"
print("Depends on MarkdownReports, gtools, readr, gdata, clipr. Some functions depend on other libraries.")
### Load the MarkdownReports Library -------------------------------------------------------------------------------------------------
# source("~/Github/MarkdownReports/MarkdownReports/R/MarkdownReports.R")
# try(require("MarkdownReports"))
# try(require("gtools"))
# try(ggplot2::theme_set( theme_bw()), silent = TRUE)
# Alisases ----------------
sort.natural = gtools::mixedsort
p0 = paste0
l = length
ppp <- function(...) { paste(..., sep = '.') } # Paste by point
pps <- function(...) { paste(..., sep = '/') } # Paste by (forward) slash
ppu <- function(...) { paste(..., sep = '_') } # Paste by underscore
ppd <- function(...) { paste(..., sep = '-') } # Paste by dash
kpp <- function(...) { paste(..., sep = '.', collapse = '.') } # kollapse by point
kppu <- function(...) { paste(..., sep = '_', collapse = '_') } # kollapse by underscore
kpps <- function(...) { paste(..., sep = '/', collapse = '/') } # kollapse by (forward) slash
kppd <- function(...) { paste(..., sep = '-', collapse = '-') } # kollapse by dash
sppp <- function(...) { # Simplified Paste by point
string <- paste(..., sep = '.')
gsub(pattern = '\\.+', replacement = '\\.', x = string)
}
stry <- function(...) {try(..., silent = T)} # Silent try
## Generic -------------------------------------------------------------------------------------------------
'%!in%' <- function(x,y)!('%in%'(x,y))
stopif2 <- function(condition, ...) { if (condition) {iprint(...); stop()} } # Stop script if the condition is met. You can parse anything (e.g. variables) in the message
say <- function(...) { # Use system voice to notify (after a long task is done)
sys <- Sys.info()["sysname"]
if (sys == "Darwin") system("say Ready")
if (sys == "Linux") system("echo -e '\a'; sleep 0.5s; echo -e '\a'; sleep 0.5s; echo -e '\a'; sleep 0.5s; echo -e '\a'; sleep 0.5s; echo -e '\a'; sleep 0.5s; echo -e '\a'") # For UNIX servers.
}
sayy <- function(...) {system("say Ready to roll")} # Use system voice to notify (after a long task is done)
grepv <- function(pattern, x, ignore.case = FALSE, perl = FALSE, value = FALSE, fixed = FALSE, useBytes = FALSE # grep returning the value
, invert = FALSE, ...) grep(pattern, x, ignore.case = ignore.case, perl = perl, fixed = fixed
, useBytes = useBytes, invert = invert, ..., value = TRUE)
oo <- function() { # Open current working directory.
system("open .")
}
# detach_package <-
unload <- function(pkg, character.only = FALSE) { # Unload a package. Source: https://stackoverflow.com/questions/6979917/how-to-unload-a-package-without-restarting-r
if (!character.only)
{
pkg <- deparse(substitute(pkg))
}
search_item <- paste("package", pkg, sep = ":")
while (search_item %in% search())
{
detach(search_item, unload = TRUE, character.only = TRUE)
}
}
most_frequent_elements <- function(thingy, topN = 10) { # Show the most frequent elements of a table
tail(sort(table(thingy, useNA = "ifany")), topN)
}
top_indices <- function(x, n = 3, top = TRUE) { # Returns the position / index of the n highest values. For equal values, it maintains the original order
head( order(x, decreasing = top), n )
}
percentile2value <- function(distribution, percentile = 0.95, FirstValOverPercentile = TRUE) { # Calculate what is the actual value of the N-th percentile in a distribution or set of numbers. Useful for calculating cutoffs, and displaying them by whist()'s "vline" paramter.
index = percentile * length(distribution)
if (FirstValOverPercentile) { index = ceiling(index)
} else {index = floor(index) }
value = sort(distribution)[index]
return(value)
}
printEveryN <- function(i, N = 1000) { if ((i %% N) == 0 ) iprint(i) } # Report at every e.g. 1000
irequire <- function(package) { package_ = as.character(substitute(package)); print(package_); # Load a package. If it does not exist, try to install it from CRAN.
if (!require(package = package_, character.only = TRUE)) {
print("Not Installed yet.");install.packages(pkgs = package_);
Sys.sleep(1)
print("Loading package:")
require(package = package_, character.only = TRUE)
}
} # install package if cannot be loaded
idate <- function(Format = c("%Y.%m.%d_%H.%M", "%Y.%m.%d_%Hh")[2]) { format(Sys.time(), format = Format ) } # Parse current date, dot separated.
view.head <- function(matrix, enn = 10) { matrix[1:min(NROW(matrix), enn), 1:min(NCOL(matrix), enn)] } # view the head of an object by console.
view.head2 <- function(matrix, enn = 10) { View(head(matrix, n = min(NROW(matrix), NCOL(matrix), enn))) } # view the head of an object by View().
iidentical.names <- function(v1, v2) { # Test if names of two objects for being exactly equal
nv1 = names(v1)
nv2 = names(v2)
len.eq = (length(nv1) == length(nv2))
if (!len.eq) iprint("Lenghts differ by:", (length(nv1) - length(nv2)) )
Check = identical(nv1, nv2)
if (!Check) {
diff = setdiff(nv1, nv2)
ld = length(diff)
iprint(ld, "elements differ: ", head(diff))
}
Check
}
iidentical <- function(v1, v2) { # Test if two objects for being exactly equal
len.eq = (length(v1) == length(v2))
if (!len.eq) iprint("Lenghts differ by:", (length(v1) - length(v2)) )
Check = identical(v1,v2)
if (!Check) {
diff = setdiff(v1, v2)
ld = length(diff)
iprint(ld, "elements differ: ", head(diff))
}
Check
}
iidentical.all <- function(li) all(sapply(li, identical, li[[1]])) # Test if two objects for being exactly equal.
#' IfExistsAndTrue
#'
#' Internal function. Checks if a variable is defined, and its value is TRUE.
#' @param name Name of the varaible
#' @export
#' @examples IfExistsAndTrue()
IfExistsAndTrue <- function(name = "pi" ) { # Internal function. Checks if a variable is defined, and its value is TRUE.
x = FALSE
if (exists(name)) {
if (isTRUE(get(name))) {x = TRUE} else {x = FALSE; iprint(name, " exists, but != TRUE; ", get(name))}
}
return(x)
}
memory.biggest.objects <- function(n = 5, saveplot = F) { # Show distribution of the largest objects and return their names. # https://stackoverflow.com/questions/17218404/should-i-get-a-habit-of-removing-unused-variables-in-r
try.dev.off()
gc()
ls.mem <- ls( envir = .GlobalEnv)
ls.obj <- lapply(ls.mem, get)
Sizes.of.objects.in.mem <- unlapply(ls.obj, object.size)
names(Sizes.of.objects.in.mem) <- ls.mem
topX = sort(Sizes.of.objects.in.mem,decreasing = TRUE)[1:n]
Memorty.usage.stat = c(topX, 'Other' = sum(sort(Sizes.of.objects.in.mem,decreasing = TRUE)[-(1:n)]))
pie(Memorty.usage.stat, cex = .5, sub = make.names(date()))
try(qpie(Memorty.usage.stat, w = 7, ), silent = T)
# Use wpie if you have MarkdownReports, from https://github.com/vertesy/MarkdownReports
dput(names(topX))
iprint("rm(list = c( 'objectA', 'objectB'))")
# inline_vec.char(names(topX))
# Use inline_vec.char if you have DataInCode, from https://github.com/vertesy/DataInCode
}
# memory.biggest.objects()
## File handling, export, import [read & write] -------------------------------------------------------------------------------------------------
### Reading files in -------------------------------------------------------------------------------------------------
read.simple.vec <- function(...) { # Read each line of a file to an element of a vector (read in new-line separated values, no header!).
pfn = kollapse(...) # merge path and filename
read_in = as.vector(unlist(read.table( pfn , stringsAsFactors = FALSE, sep = "\n" )) )
iprint(length(read_in), "elements")
return(read_in);
}
read.simple <- function(...) { # It is essentially read.table() with file/path parsing.
pfn = kollapse(...) # merge path and filename
read_in = read.table( pfn , stringsAsFactors = FALSE)
return(read_in)
}
read.simple_char_list <- function(...) { # Read in a file.
pfn = kollapse(...) # merge path and filename
read_in = unlist(read.table( pfn , stringsAsFactors = FALSE ) )
iprint("New variable head: ", what(read_in))
return(read_in)
}
read.simple.table <- function(..., colnames = TRUE, coltypes = NULL) { # Read in a file. default: header defines colnames, no rownames. For rownames give the col nr. with rownames, eg. 1 The header should start with a TAB / First column name should be empty.
pfn = kollapse(...) # merge path and filename
# read_in = read.table( pfn , stringsAsFactors = FALSE, sep = "\t", header = colnames )
read_in = readr::read_tsv( pfn, col_names = colnames, col_types = coltypes )
iprint("New variable dim: ", dim(read_in))
read_in = as.data.frame(gtools::na.replace(data.matrix(read_in), replace = 0))
return(read_in)
}
FirstCol2RowNames <- function(Tibble, rownamecol = 1, make_names = FALSE, convert.2.df = FALSE ) { # Set First Col to Row Names
(NN = Tibble[[rownamecol]])
(Tibble <- Tibble[, -rownamecol, drop = F])
if (convert.2.df) Tibble = as.data.frame(Tibble) else iprint('Rownames of tibble assigned:', head(NN))
rownames(Tibble) = if (make_names) make.names(NN, unique = TRUE) else NN
return(Tibble)
}
# xyz <- tibble(v1 = c("a", "a", "b", "b"), v2 = c(3,3,4,4), v3 = c(11,21,31,41)); FirstCol2RowNames(xyz, make_names = T)
read.simple.tsv <- function(..., sep_ = "\t", colnames = TRUE, wRownames = TRUE, coltypes = NULL, NaReplace = TRUE) { # Read in a file with excel style data: rownames in col1, headers SHIFTED. The header should start with a TAB / First column name should be empty.
pfn = kollapse(...) # merge path and filename
# read_in = read.delim( pfn , stringsAsFactors = FALSE, sep = , sep_, row.names = 1, header = TRUE )
read_in = suppressWarnings(readr::read_tsv( pfn, col_names = colnames, col_types = coltypes ))
iprint("New variable dim: ", dim(read_in) - 0:1)
if (wRownames) { read_in = FirstCol2RowNames(read_in) }
if (NaReplace) { read_in = as.data.frame(gtools::na.replace(read_in, replace = 0)) }
return(read_in)
}
read.simple.csv <- function(..., colnames = TRUE, coltypes = NULL, wRownames = TRUE, NaReplace = TRUE, nmax = Inf) { # Read in a file with excel style data: rownames in col1, headers SHIFTED. The header should start with a TAB / First column name should be empty.
pfn = kollapse(...) # merge path and filename
read_in = suppressWarnings(readr::read_csv( pfn, col_names = colnames, col_types = coltypes, n_max = nmax ))
iprint("New variable dim: ", dim(read_in) - 0:1)
if (wRownames) { read_in = FirstCol2RowNames(read_in) }
if (NaReplace) { read_in = as.data.frame(gtools::na.replace(read_in, replace = 0)) }
return(read_in)
}
read.simple.ssv <- function(..., sep_ = " ", colnames = TRUE, wRownames = TRUE, NaReplace = TRUE, coltypes = NULL) { # Space separeted values. Read in a file with excel style data: rownames in col1, headers SHIFTED. The header should start with a TAB / First column name should be empty.
pfn = kollapse(...) # merge path and filename
read_in = suppressWarnings(readr::read_delim( pfn, delim = sep_, col_names = colnames, col_types = coltypes ))
iprint("New variable dim: ", dim(read_in) - 0:1)
if (wRownames) { read_in = FirstCol2RowNames(read_in) }
if (NaReplace) { read_in = as.data.frame(gtools::na.replace(read_in, replace = 0)) }
return(read_in)
}
read.simple.tsv.named.vector <- function(...) { # Read in a file with excel style named vectors, names in col1, headers SHIFTED. The header should start with a TAB / First column name should be empty.
pfn = kollapse(...) # merge path and filename
# read_in = read.delim( pfn , stringsAsFactors = FALSE, sep = sep_, row.names = 1, header = TRUE )
read_in = readr::read_tsv( pfn )
vect = read_in[[2]]
names(vect) = read_in[[1]]
iprint("New vectors length is: ", length(vect))
return(vect)
}
convert.tsv.data <- function(df_by_read.simple.tsv = x, digitz = 2, na_rep = 0 ) { # Fix NA issue in dataframes imported by the new read.simple.tsv. Set na_rep to NA if you want to keep NA-s
DAT = data.matrix(df_by_read.simple.tsv)
SNA = sum(is.na(DAT))
try(iprint("Replaced NA values:", SNA, "or", percentage_formatter(SNA/length(DAT))), silent = TRUE)
gtools::na.replace(round(DAT, digits = digitz), replace = na_rep)
}
read.simple.xls <- function(pfn = kollapse(...), row_namePos = NULL, ..., header_ = TRUE, WhichSheets) { # Read multi-sheet excel files. row_namePos = NULL for automatic names Look into: http://readxl.tidyverse.org/.
if (!require("gdata")) { print("Please install gplots: install.packages('gdata')") }
if (grepl("^~/", pfn)) {
iprint("You cannot use the ~/ in the file path! It is replaced by '/Users/abel.vertesy/'.")
pfn = gsub(pattern = "^~/", replacement = "/Users/abel.vertesy/", x = pfn)
} else {print(pfn)}
if (!require("gdata")) { print("Please install gplots: install.packages('gdata')") }
# merge path and filename
TheSheetNames = sheetNames(pfn, verbose = FALSE);
NrSheets = length(TheSheetNames)
iprint(NrSheets, "sheets in the file.")
ExpData = list.fromNames(TheSheetNames)
RangeOfSheets = if (missing(WhichSheets)) 1:NrSheets else WhichSheets
for (i in RangeOfSheets ) {
iprint("sheet", i)
ExpData[[i]] = gdata::read.xls(pfn, sheet = i, row.names = row_namePos, header = header_)
} #for
lapply(ExpData, function(x) print(dimnames(x)) )
return(ExpData);
}
sourcePartial <- function(fn,startTag = '#1', endTag = '#/1') { # Source parts of another script. Source: https://stackoverflow.com/questions/26245554/execute-a-set-of-lines-from-another-r-file
lines <- scan(fn, what = character(), sep = "\n", quiet = TRUE)
st <- grep(startTag,lines)
en <- grep(endTag,lines)
tc <- textConnection(lines[(st + 1):(en - 1)])
source(tc)
close(tc)
}
### Writing files out -------------------------------------------------------------------------------------------------
write.simple <- function(input_df, extension = 'tsv', ManualName = "", o = FALSE, ... ) { # Write out a matrix-like R-object to a file with as tab separated values (.tsv). Your output filename will be either the variable's name. The output file will be located in "OutDir" specified by you at the beginning of the script, or under your current working directory. You can pass the PATH and VARIABLE separately (in order), they will be concatenated to the filename.
fname = kollapse(...) ; if (nchar(fname) < 2 ) { fname = substitute(input_vec) }
if (nchar(ManualName)) {FnP = kollapse(ManualName)} else {FnP = ww.FnP_parser(fname, extension) }
write.table(input_df, file = FnP, sep = "\t", row.names = FALSE, col.names = TRUE, quote = FALSE)
if (o) { system(paste0("open ", FnP), wait = FALSE) }
iprint("Length: ", length(input_df))
} # fun
write.simple.vec <- function(input_vec, extension = 'vec', ManualName = "", o = FALSE, ... ) { # Write out a vector-like R-object to a file with as newline separated values (.vec). Your output filename will be either the variable's name. The output file will be located in "OutDir" specified by you at the beginning of the script, or under your current working directory. You can pass the PATH and VARIABLE separately (in order), they will be concatenated to the filename.
fname = kollapse(...) ; if (nchar(fname) < 2 ) { fname = substitute(input_vec) }
if (nchar(ManualName)) {FnP = kollapse(ManualName)} else {FnP = ww.FnP_parser(fname, extension) }
write.table(input_vec, file = FnP, sep = "\t", row.names = FALSE, col.names = FALSE, quote = FALSE )
iprint("Length: ", length(input_vec))
if (o) { system(paste0("open ", FnP), wait = FALSE) }
} # fun
write.simple.xlsx <- function(named_list, ManualName = "", o = FALSE, ..., TabColor = "darkgoldenrod1", Creator = "Vertesy",# Write out a list of matrices/ data frames WITH ROW- AND COLUMN- NAMES to a file with as an Excel (.xslx) file. Your output filename will be either the variable's name. The output file will be located in "OutDir" specified by you at the beginning of the script, or under your current working directory. You can pass the PATH and VARIABLE separately (in order), they will be concatenated to the filename.
HeaderCex = 12, HeaderLineColor = "darkolivegreen3", HeaderCharStyle = c("bold", "italic", "underline")[1] ) {
irequire(openxlsx)
fname = if (nchar(ManualName) < 2 ) { fname = substitute(named_list) }
if (nchar(ManualName)) {FnP = kollapse(ManualName)} else {FnP = ww.FnP_parser(fname, "xlsx") }
hs <- createStyle(textDecoration = HeaderCharStyle, fontSize = HeaderCex, fgFill = HeaderLineColor)
setwd(OutDir)
openxlsx::write.xlsx(named_list, file = ppp(fname,"xlsx"), rowNames = TRUE, firstRow = TRUE, firstCol = TRUE, colWidths = "auto"
, headerStyle = hs, tabColour = TabColor, creator = Creator) #
if (o) { system(paste0("open ", FnP), wait = FALSE) }
} # fun
write.simple.append <- function(input_df, extension = 'tsv', ManualName = "", o = FALSE, ... ) { # Append an R-object WITHOUT ROWNAMES, to an existing .tsv file of the same number of columns. Your output filename will be either the variable's name. The output file will be located in "OutDir" specified by you at the beginning of the script, or under your current working directory. You can pass the PATH and VARIABLE separately (in order), they will be concatenated to the filename.
fname = kollapse(...) ; if (nchar(fname) < 2 ) { fname = substitute(input_df) }
if (nchar(ManualName)) { FnP = kollapse(ManualName)} else {FnP = ww.FnP_parser(fname, extension) }
write.table(input_df, file = FnP, sep = "\t", row.names = FALSE, col.names = FALSE, quote = FALSE, append = TRUE )
if (o) { system(paste0("open ", FnP), wait = FALSE) }
} # fun
jjpegA4 <- function(filename, r = 225, q = 90) { # Setup an A4 size jpeg
jpeg(file = filename,width = wA4, height = hA4, units = 'in', quality = q,res = r)
}
extPDF <- function(vec) ppp(vec, "pdf") # add pdf as extension to a file name
extPNG <- function(vec) ppp(vec, "png") # add png as extension to a file name
### Clipboard interaction -------------------------------------------------------------------------------------------------
# https://github.com/vertesy/DataInCode
# try(source("~/Github/TheCorvinas/R/DataInCode/DataInCode.R"), silent = FALSE)
clip2clip.vector <- function() { # Copy from clipboard (e.g. excel) to a R-formatted vector to the clipboard
x = dput(clipr::read_clip() )
clipr::write_clip(
utils::capture.output(x)
)
print(x)
}
clip2clip.commaSepString <- function() { # Read a comma separated string (e.g. list of gene names) and properly format it for R.
x = unlist(strsplit(clipr::read_clip(), split = ','))
clipr::write_clip(
utils::capture.output(x)
)
print(x)
}
write_clip.replace.dot <- function(var = df.markers, decimal_mark = ',') { # Clipboard export for da wonderful countries with where "," is the decimal
write_clip(format(var, decimal.mark = decimal_mark) )
}
# write_clip.replace.dot(df_markers)
## Create and check variables -------------------------------------------------------------------------------------------------
vec.fromNames <- function(name_vec = LETTERS[1:5], fill = NA) { # create a vector from a vector of names
v = numeric(length(name_vec))
if (length(fill) == 1) {v = rep(fill, length(name_vec))}
else if (length(fill == length(name_vec))) {v = fill}
names(v) = name_vec
return(v)
}
list.fromNames <- function(name_vec = LETTERS[1:5], fill = NaN) { # create list from a vector with the names of the elements
liszt = as.list(rep(fill, length(name_vec)))
names(liszt) = name_vec
return(liszt)
}
matrix.fromNames <- function(rowname_vec = 1:10, colname_vec = LETTERS[1:5], fill = NA) { # Create a matrix from 2 vectors defining the row- and column names of the matrix. Default fill value: NA.
mx = matrix(data = fill, nrow = length(rowname_vec), ncol = length(colname_vec), dimnames = list(rowname_vec, colname_vec))
iprint("Dimensions:", dim(mx))
return(mx)
}
matrix.fromVector <- function(vector = 1:5, HowManyTimes = 3, IsItARow = TRUE) { # Create a matrix from values in a vector repeated for each column / each row. Similar to rowNameMatrix and colNameMatrix.
matt = matrix(vector, nrow = length(vector), ncol = HowManyTimes)
if ( !IsItARow ) {matt = t(matt)}
return(matt)
}
array.fromNames <- function(rowname_vec = 1:3, colname_vec = letters[1:2], z_name_vec = LETTERS[4:6], fill = NA) { # create an N-dimensional array from N vectors defining the row-, column, etc names of the array
DimNames = list(rowname_vec, colname_vec, z_name_vec)
Dimensions_ = lapply(DimNames, length)
mx = array(data = fill, dim = Dimensions_, dimnames = DimNames)
iprint("Dimensions:", dim(mx))
return(mx)
}
what <- function(x, printme = 0) { # A better version of is(). It can print the first "printme" elements.
iprint(is(x), "; nr. of elements:", length(x))
if ( is.numeric(x) ) { iprint("min&max:", range(x) ) } else {print("Not numeric")}
if ( length(dim(x) ) > 0 ) { iprint("Dim:", dim(x) ) }
if ( printme > 0) { iprint("Elements:", x[0:printme] ) }
head(x)
}
idim <- function(any_object) { # A dim() function that can handle if you pass on a vector: then, it gives the length.
if (is.null(dim(any_object))) {
if (is.list(any_object)) { print("list") } #if
print(length(any_object))
}
else { print(dim(any_object)) }
}
idimnames <- function(any_object) { # A dimnames() function that can handle if you pass on a vector: it gives back the names.
if (!is.null(dimnames(any_object))) { print(dimnames(any_object)) }
else if (!is.null(colnames(any_object))) { iprint("colnames:", colnames(any_object)) }
else if (!is.null(rownames(any_object))) { iprint("rownames:", rownames(any_object)) }
else if (!is.null(names(any_object))) { iprint("names:", names(any_object)) }
}
table_fixed_categories <- function(vector, categories_vec) { # generate a table() with a fixed set of categories. It fills up the table with missing categories, that are relevant when comparing to other vectors.
if ( !is.vector(vector)) {print(is(vector[]))}
table(factor(unlist(vector), levels = categories_vec))
}
## Vector operations -------------------------------------------------------------------------------------------------
trail <- function(vec, N = 10) c(head(vec, n = N), tail(vec, n = N) ) # A combination of head() and tail() to see both ends.
sort.decreasing <- function(vec) sort(vec, decreasing = TRUE) # Sort in decreasing order.
sstrsplit <- function(string, pattern = "_", n = 2) { stringr::str_split_fixed(string, pattern = pattern, n = n) } # Alias for str_split_fixed in the stringr package
topN.dfCol <- function(df_Col = as.named.vector(df[ , 1, drop = FALSE]), n = 5) { head(sort(df_Col, decreasing = TRUE), n = n) } # Find the n highest values in a named vector
bottomN.dfCol <- function(df_Col = as.named.vector(df[ , 1, drop = FALSE]), n = 5) { head(sort(df_Col, decreasing = FALSE), n = n) } # Find the n lowest values in a named vector
as.named.vector <- function(df_col, WhichDimNames = 1) { # Convert a dataframe column or row into a vector, keeping the corresponding dimension name.
print('2-colDF: tibble::deframe(); It converts the first column to names and second column to values.')
# use RowNames: WhichDimNames = 1 , 2: use ColNames
# !!! might require drop = FALSE in subsetting!!! eg: df_col[, 3, drop = FALSE]
# df_col[which(unlist(lapply(df_col, is.null)))] = "NULL" # replace NULLs - they would fall out of vectors - DOES not work yet
namez = dimnames(df_col)[[WhichDimNames]]
if (is.list(df_col) & !is.data.frame(df_col)) {namez = names(df_col)}
vecc = as.vector(unlist(df_col))
names(vecc) = namez
return(vecc)
}
# df2named.vector <- function(df_columns, names=1, data=2) {
#
# }
col2named.vector <- function(df_col) { # Convert a dataframe column into a vector, keeping the corresponding dimension name.
namez = rownames(df_col)
vecc = as.vector(unlist(df_col))
names(vecc) = namez
return(vecc)
}
row2named.vector <- function(df_row) { # Convert a dataframe row into a vector, keeping the corresponding dimension name.
namez = colnames(df_row)
vecc = as.vector(unlist(df_row))
names(vecc) = namez
return(vecc)
}
tibble_summary_to_named_vec <- function(tbl = dplyr::tibble('key' = sample(x = 1:5, size = 20, replace = T), 'value' = rnorm(20) )
, idx = c(key =1, value = 2)) { # Convert a key-value tibble into a named vector (as opposed to using rownames).
iprint("The following name and value columns are taken:",colnames(tbl[idx]), "; with indices:", idx)
tbl_2_col <- tbl[,idx]
named.vec <- tbl_2_col[[2]]
names(named.vec) <- tbl_2_col[[1]]
return(named.vec)
}
# tibble_summary_to_named_vec()
as_tibble_from_named_vec <- function(vec.w.names = c("a" = 1, "b" = 2), transpose = T) { # Convert a vector with names into a tibble, keeping the names as rownames.
stopif(is_null(names(vec.w.names)))
tbl <- bind_rows(vec.w.names)
if (transpose) t(tbl) else tbl
}
# as_tibble_from_named_vec()
as.numeric.wNames <- function(vec) { # Converts any vector into a numeric vector, and puts the original character values into the names of the new vector, unless it already has names. Useful for coloring a plot by categories, name-tags, etc.
numerified_vec = as.numeric(as.factor(vec)) - 1 # as factor gives numbers [1:n] instead [0:n]
if (!is.null(names(vec))) {names(numerified_vec) = names(vec)}
return(numerified_vec)
}
as.numeric.wNames.old <- function(vec) { # Converts any vector into a numeric vector, and puts the original character values into the names of the new vector, unless it already has names. Useful for coloring a plot by categories, name-tags, etc.
numerified_vec = as.numeric(as.factor(vec))
if (!is.null(names(vec))) {names(numerified_vec) = names(vec)}
return(numerified_vec)
}
as.character.wNames <- function(vec) { # Converts your input vector into a character vector, and puts the original character values into the names of the new vector, unless it already has names.
char_vec = as.character(vec)
if (!is.null(names(vec))) {names(char_vec) = names(vec)}
return(char_vec)
}
rescale <- function(vec, from = 0, upto = 100) { # linear transformation to a given range of values
vec = vec - min(vec, na.rm = TRUE)
vec = vec * ((upto - from)/max(vec, na.rm = TRUE))
vec = vec + from
return(vec)
} # fun
flip_value2name <- function(named_vector, NumericNames = FALSE, silent = F) { # Flip the values and the names of a vector with names
if (!is.null(names(named_vector))) {
newvec = names(named_vector)
if (NumericNames) { newvec = as.numeric(names(named_vector)) }
names(newvec) = named_vector
} else {llprint("Vector without names!", head(named_vector))}
if (!silent) {
if (any(duplicated(named_vector))) {iprint("New names contain duplicated elements", head(named_vector[which(duplicated(named_vector))])) }
if (any(duplicated(newvec))) {iprint("Old names contained duplicated elements", head(newvec[which(duplicated(newvec))])) }
}
return(newvec)
}
value2name_flip = flip_value2name
sortbyitsnames <- function(vec_or_list, decreasing = FALSE, ...) { # Sort a vector by the alphanumeric order of its names(instead of its values).
xx = names(vec_or_list)
names(xx) = 1:length(vec_or_list)
order = as.numeric(names(gtools::mixedsort(xx, decreasing = decreasing, ...)))
vec_or_list[order]
}
any.duplicated <- function(vec, summarize = TRUE) { # How many entries are duplicated
y = sum(duplicated(vec))
if (summarize & y) {
x = table(vec); x = x[x > 1] - 1;
print("The following elements have > 1 extra copies:")
print(x) # table formatting requires a separate entry
}
return(y)
}
which.duplicated <- function(vec, orig = F) { # which values are duplicated?
DPL = vec[which(duplicated(vec))]; iprint(length(DPL), "Duplicated entries: ", DPL)
# for (i in DPL ) { print(grepv(i,orig)) } #for
return(DPL)
}
which.NA <- function(vec, orig = F) { # which values are NA?
NANs = vec[which(is.na(vec))]; iprint(length(NANs), "NaN entries: ", NANs)
NAs = vec[which(is.na(vec))]; iprint(length(NAs), "NA entries: ", NAs, "(only NA-s are returned)")
# for (i in DPL ) { print(grepv(i,orig)) } #for
return(NAs)
}
pad.na <- function(x, len) { c(x, rep(NA, len - length(x))) } # Fill up with a vector to a given length with NA-values at the end.
clip.values <- function(valz, high = TRUE, thr = 3) { # Signal clipping. Cut values above or below a threshold.
if (high) { valz[valz > thr] = thr
} else { valz[valz < thr] = thr }
valz
}
clip.outliers <- function(valz, high = TRUE, probs = c(.01, .99), na.rm = TRUE, showhist = FALSE, ...) { # Signal clipping based on the input data's distribution. It clips values above or below the extreme N% of the distribution.
qnt <- quantile(valz, probs = probs, na.rm = na.rm)
if (showhist) { whist(unlist(valz), breaks = 50 ,vline = qnt, filtercol = -1)} #if
y <- valz
y[valz < qnt[1]] <- qnt[1]
y[valz > qnt[2]] <- qnt[2]
y
}
#' as.logical.wNames
#'
#' Converts your input vector into a logical vector, and puts the original character values
#' into the names of the new vector, unless it already has names.
#' @param x A vector with names that will be converted to a logical vector
#' @param ... Pass any other argument.
#' @export
#' @examples x = -1:2; names(x) = LETTERS[1:4]; as.logical.wNames(x)
as.logical.wNames <- function(x, ...) { # Converts your input vector into a logical vector, and puts the original character values into the names of the new vector, unless it already has names.
numerified_vec = as.logical(x, ...)
if (!is.null(names(x))) {names(numerified_vec) = names(x)}
return(numerified_vec)
}
col2named.vec.tbl <- function(tbl.2col) { # Convert a 2-column table(data frame) into a named vector. 1st column will be used as names.
nvec = tbl.2col[[2]]
names(nvec) = tbl.2col[[1]]
nvec
}
iterBy.over <- function(yourvec, by = 9) { # Iterate over a vector by every N-th element.
steps = ceiling(length(yourvec)/by)
lsX = split(yourvec, sort(rank(yourvec) %% steps))
names(lsX) = 1:length(lsX)
lsX
} # for (i in iterBy.over(yourvec = x)) { print(i) }
zigzagger <- function(vec = 1:9) { # mix entries so that they differ
intermingle2vec(vec, rev(vec))[1:length(vec)]
}
numerate <- function(x = 1, y = 100, zeropadding = TRUE, pad_length = floor( log10( max(abs(x), abs(y)) ) ) + 1) { # numerate from x to y with additonal zeropadding
z = x:y
if (zeropadding) { z = stringr::str_pad(z, pad = 0, width = pad_length) }
return(z)
}
# (numerate(1, 122))
MaxN <- function(vec = rpois(4, lambda = 3), topN = 2) { # find second (third…) highest/lowest value in vector
topN = topN - 1
n <- length(vec)
sort(vec, partial = n - topN)[n - topN]
}
# https://stackoverflow.com/questions/2453326/fastest-way-to-find-second-third-highest-lowest-value-in-vector-or-column
cumsubtract <- function(numericV = blanks) { # Cumulative subtraction, opposite of cumsum()
DiffZ = numericV[-1] - numericV[-length(numericV)]
print(table(DiffZ))
DiffZ
}
sumBySameName <- function(namedVec) { # Sum up vector elements with the same name
# unlapply(splitbyitsnames(namedVec), sum)
tapply(X = namedVec, INDEX = names(namedVec), sum)
}
### Vector filtering -------------------------------------------------------------------------------------------------
which_names <- function(named_Vec) { # Return the names where the input vector is TRUE. The input vector is converted to logical.
return(names(which(as.logical.wNames(named_Vec)))) }
which_rownames <- function(df_column) { # Return the rownames where the input column is TRUE.
stopifnot(length(rownames(df_column)) > 0)
idx.T <- which(df_column == TRUE)
return(rownames(df_column)[idx.T])
}
which_names_grep <- function(named_Vec, pattern) { # Return the vector elements whose names are partially matched
idx = grepv(x = names(named_Vec),pattern = pattern)
return(named_Vec[idx])
}
na.omit.strip <- function(vec, silent = FALSE) { # Calls na.omit() and returns a clean vector
if (is.data.frame(vec)) {
if (min(dim(vec)) > 1 & silent == FALSE) { iprint(dim(vec), "dimensional array is converted to a vector.") }
vec = unlist(vec) }
clean = na.omit(vec)
attributes(clean)$na.action <- NULL
return(clean)
}
inf.omit <- function(vec) { # Omit infinite values from a vector.
if (is.data.frame(vec)) {
if ( min(dim(vec)) > 1 ) { iprint(dim(vec), "dimensional array is converted to a vector.") }
vec = unlist(vec) }
clean = vec[is.finite(vec)]
# attributes(clean)$na.action <- NULL
return(clean)
}
zero.omit <- function(vec) { # Omit zero values from a vector.
v2 = vec[vec != 0]
iprint("range: ", range(v2))
if ( !is.null(names(vec)) ) {names(v2) = names(vec)[vec != 0]}
return(v2)
}
pc_TRUE <- function(logical_vector, percentify = TRUE, NumberAndPC = FALSE, NArm = TRUE, prefix = NULL, suffix = NULL) { # Percentage of true values in a logical vector, parsed as text (useful for reports.)
SUM = sum(logical_vector, na.rm = NArm)
LEN = length(logical_vector)
out = SUM / LEN
if (percentify) {out = percentage_formatter(out) }
if (NumberAndPC) { out = paste0(out, " or " , SUM, " of ", LEN) }
if (!is.null(prefix)) {out = paste(prefix, out) }
if (!is.null(suffix)) {out = paste(out, suffix) }
return(out)
}
# deprecated :
NrAndPc <- function(logical_vec = idx_localised, total = TRUE, NArm = TRUE) { # Summary stat. text formatting for logical vectors (%, length)
x = paste0(pc_TRUE(logical_vec), " or ", sum(logical_vec, na.rm = NArm))
if (total) paste0(x, " of ", length(logical_vec))
}
pc_in_total_of_match <- function(vec_or_table, category, NA_omit = TRUE) { # Percentage of a certain value within a vector or table.
if (is.table(vec_or_table)) { vec_or_table[category]/sum(vec_or_table, na.rm = NA_omit) }
else {# if (is.vector(vec_or_table))
if (NA_omit) {
if (sum(is.na(vec_or_table))) { vec_or_table = na.omit(vec_or_table); iprint(sum(is.na(vec_or_table)), 'NA are omitted from the vec_or_table of:', length(vec_or_table))}
"Not wokring complelety : if NaN is stored as string, it does not detect it"
}
sum(vec_or_table == category) / length(vec_or_table)
} # else: is vector
} # fun
filter_survival_length <- function(length_new, length_old, prepend = "") { # Parse a sentence reporting the % of filter survival.
pc = percentage_formatter(length_new/length_old)
llprint(prepend, pc, " of ", length_old, " entries make through the filter")
}
remove_outliers <- function(x, na.rm = TRUE, ..., probs = c(.05, .95)) { # Remove values that fall outside the trailing N % of the distribution.
print("Deprecated. Use clip.outliers()")
qnt <- quantile(x, probs = probs, na.rm = na.rm, ...)
# H <- 1.5 * IQR(x, na.rm = na.rm)
y <- x
# y[x < (qnt[1] - H)] <- NA ## Add IQR dependence
# y[x > (qnt[2] + H)] <- NA
y[x < qnt[1]] <- NA ## Add IQR dependence
y[x > qnt[2]] <- NA
y
}
simplify_categories <- function(category_vec, replaceit , to ) { # Replace every entry that is found in "replaceit", by a single value provided by "to"
matches = which(category_vec %in% replaceit); iprint(length(matches), "instances of", replaceit, "are replaced by", to)
category_vec[matches] = to
return(category_vec)
}
lookup <- function(needle, haystack, exact = TRUE, report = FALSE) { # Awesome pattern matching for a set of values in another set of values. Returns a list with all kinds of results.
ls_out = as.list( c(ln_needle = length(needle), ln_haystack = length(haystack), ln_hits = "", hit_poz = "", hits = "") )
Findings = numeric(0)
ln_needle = length(needle)
if (exact) {
for (i in 1:ln_needle) { Findings = c(Findings, which(haystack == needle[i]) ) } # for
} else {
for (i in 1:ln_needle) { Findings = c(Findings, grep(needle[i], haystack, ignore.case = TRUE, perl = FALSE)) } # for
} # exact or partial match
ls_out$'hit_poz' = Findings
ls_out$'ln_hits' = length(Findings)
ls_out$'hits' = haystack[Findings]
if (length(Findings)) { ls_out$'nonhits' = haystack[-Findings]
} else { ls_out$'nonhits' = haystack }
if (report) {
llprint(length(Findings), "/", ln_needle, '(', percentage_formatter(length(Findings)/ln_needle)
, ") of", substitute(needle), "were found among", length(haystack), substitute(haystack), "." )
if (length(Findings)) { llprint( substitute(needle), "findings: ", paste( haystack[Findings], sep = " " ) ) }
} else { iprint(length(Findings), "Hits:", haystack[Findings]) } # if (report)
return(ls_out)
}
## String operations -------------------------------------------------------------------------------------------------
parsepvalue <- function(pvalue = 0.01) paste0("(p<",pvalue,")"); # Parse p-value from a number to a string.
eval_parse_kollapse <- function(...) { # evaluate and parse (dyn_var_caller)
substitute(eval(parse(text = kollapse( ... , print = FALSE))))
}
param.list.2.fname <- function(ls.of.params = p) { # Take a list of parameters and parse a string from their names and values.
paste(names(ls.of.params), ls.of.params, sep = ".", collapse = "_")
}
PasteDirNameFromFlags <- function(...) { # Paste a dot (point) separated string from a list of inputs (that can be empty), and clean up the output string from dot multiplets (e.g: ..).
flagList <- c(...)
pastedFlagList <- kpp(flagList)
CleanDirName <- gsub(x = pastedFlagList, pattern = '[\\..] + ',replacement = '\\.' )
return(CleanDirName)
}
# PasteDirNameFromFlags("HCAB"
# , flag.nameiftrue(p$'premRNA')
# , flag.nameiftrue(p$"dSample.Organoids")
# , flag.names_list(p$'variables.2.regress')
# , flag.nameiftrue(p$'Man.Int.Order') )
### File name and path parsing ------------------------------------------------------------------------------------------------
PasteOutdirFromFlags <- function(path = "~/Dropbox/Abel.IMBA/AnalysisD", ...) { # Paste OutDir from (1) a path and (2) a from a list of inputs (that can be empty), and clean up the output string from dot and forward slash multiplets (e.g: ..).
flagList <- c(path, ...)
pastedFlagList <- kpp(flagList)
CleanDirName <- gsub(x = pastedFlagList, pattern = '[\\..] + ',replacement = '\\.' )
# pastedOutDir <- kpps(path, CleanDirName, "/")
pastedOutDir <- p0(CleanDirName, "/")
CleanDirName <- gsub(x = pastedOutDir, pattern = '[//] + ',replacement = '/' )
return(CleanDirName)
}
# PasteOutdirFromFlags("~/Dropbox/Abel.IMBA/AnalysisD/HCAB"
# , flag.nameiftrue(p$'premRNA')
# , flag.nameiftrue(p$"dSample.Organoids")
# , flag.names_list(p$'variables.2.regress')
# , flag.nameiftrue(p$'Man.Int.Order') )
flag.name_value <- function(toggle, Separator = "_") { # Returns the name and its value, if its not FALSE.
if (!isFALSE(toggle)) {
output = paste(substitute(toggle), toggle, sep = Separator)
if (length(output) > 1) output = output[length(output)] # fix for when input is a list element like p$'myparam'
return(output)
}
}
# Xseed = p$'seed' = F; flag.name_value(Xseed); flag.name_value(p$'seed')
flag.nameiftrue <- function(toggle, prefix = NULL, suffix = NULL, name.if.not = "") { # Returns the name and its value, if its TRUE.
output = if (toggle) { paste0(prefix, (substitute(toggle)), suffix)
} else {paste0(prefix, name.if.not, suffix)}
if (length(output) > 1) output = output[length(output)] # fix for when input is a list element like p$'myparam'
return(output)
} # returns the name if its value is true
nameiftrue = flag.nameiftrue # backward compatible
flag.names_list <- function(par = p$'umap.min_dist') { # Returns the name and value of each element in a list of parameters.
if (length(par)) paste(substitute(par), kppu(par) , sep = "_")[[3]]
}; # param.list.flag(par = p$umap.n_neighbors)
flag.names_list.all.new <- function(pl = p.hm) { # Returns the name and value of each element in a list of parameters.
# if (length(pl)) paste(kppu(names(pl)), kppu(pl) , sep = "_")
if (length(pl)) kppd(paste(names(pl), pl, sep = "_"))
}
param.list.flag <- function(par = p$'umap.min_dist') { # Returns the name and value of each element in a list of parameters.
paste(substitute(par), par, sep = "_")[[3]]
}; # param.list.flag(par = p$umap.n_neighbors)
## Matrix operations -------------------------------------------------------------------------------------------------
### Matrix calculations -------------------------------------------------------------------------------------------------
rowMedians <- function(x, na.rm = TRUE) apply(data.matrix(x), 1, median, na.rm = na.rm) # Calculates the median of each row of a numeric matrix / data frame.
colMedians <- function(x, na.rm = TRUE) apply(data.matrix(x), 2, median, na.rm = na.rm) # Calculates the median of each column of a numeric matrix / data frame.
rowGeoMeans <- function(x, na.rm = TRUE) apply(data.matrix(x), 1, geomean, na.rm = na.rm) # Calculates the median of each row of a numeric matrix / data frame.
colGeoMeans <- function(x, na.rm = TRUE) apply(data.matrix(x), 2, geomean, na.rm = na.rm) # Calculates the median of each column of a numeric matrix / data frame.
# depend on cv in MarkdownReports
rowCV <- function(x, na.rm = TRUE) apply(data.matrix(x), 1, cv, na.rm = na.rm ) # Calculates the CV of each ROW of a numeric matrix / data frame.
colCV <- function(x, na.rm = TRUE) apply(data.matrix(x), 2, cv, na.rm = na.rm ) # Calculates the CV of each column of a numeric matrix / data frame.
rowVariance <- function(x, na.rm = TRUE) apply(data.matrix(x), 1, var, na.rm = na.rm ) # Calculates the CV of each ROW of a numeric matrix / data frame.
colVariance <- function(x, na.rm = TRUE) apply(data.matrix(x), 2, var, na.rm = na.rm ) # Calculates the CV of each column of a numeric matrix / data frame.
rowMin <- function(x, na.rm = TRUE) apply(data.matrix(x), 1, min, na.rm = na.rm) # Calculates the minimum of each row of a numeric matrix / data frame.
colMin <- function(x, na.rm = TRUE) apply(data.matrix(x), 2, min, na.rm = na.rm) # Calculates the minimum of each column of a numeric matrix / data frame.
rowMax <- function(x, na.rm = TRUE) apply(data.matrix(x), 1, max, na.rm = na.rm) # Calculates the maximum of each row of a numeric matrix / data frame.
colMax <- function(x, na.rm = TRUE) apply(data.matrix(x), 2, max, na.rm = na.rm) # Calculates the maximum of each column of a numeric matrix / data frame.
rowSEM <- function(x, na.rm = TRUE) apply(data.matrix(x), 1, sem, na.rm = na.rm) # Calculates the SEM of each row of a numeric matrix / data frame.
colSEM <- function(x, na.rm = TRUE) apply(data.matrix(x), 2, sem, na.rm = na.rm) # Calculates the SEM of each column of a numeric matrix / data frame.
rowSD <- function(x, na.rm = TRUE) apply(data.matrix(x), 1, sd, na.rm = na.rm) # Calculates the SEM of each row of a numeric matrix / data frame.
colSD <- function(x, na.rm = TRUE) apply(data.matrix(x), 2, sd, na.rm = na.rm) # Calculates the SEM of each column of a numeric matrix / data frame.
rowIQR <- function(x, na.rm = TRUE) apply(data.matrix(x), 1, IQR, na.rm = na.rm) # Calculates the SEM of each row of a numeric matrix / data frame.
colIQR <- function(x, na.rm = TRUE) apply(data.matrix(x), 2, IQR, na.rm = na.rm) # Calculates the SEM of each column of a numeric matrix / data frame.
rowquantile <- function(x, na.rm = TRUE, ...) apply(data.matrix(x), 1, quantile, ..., na.rm = na.rm) # Calculates the SEM of each row of a numeric matrix / data frame.
colquantile <- function(x, na.rm = TRUE, ...) apply(data.matrix(x), 2, quantile, ..., na.rm = na.rm) # Calculates the SEM of each column of a numeric matrix / data frame.
colDivide <- function(mat, vec) { # divide by column # See more: https://stackoverflow.com/questions/20596433/how-to-divide-each-row-of-a-matrix-by-elements-of-a-vector-in-r
stopifnot(NCOL(mat) == length(vec))
mat / vec[col(mat)] # fastest
}
colMutliply <- function(mat, vec) { # Mutliply by column # See more: https://stackoverflow.com/questions/20596433/how-to-divide-each-row-of-a-matrix-by-elements-of-a-vector-in-r
stopifnot(NCOL(mat) == length(vec))
mat * vec[col(mat)] # fastest
}
rowDivide <- function(mat, vec) { # divide by row
stopifnot(NROW(mat) == length(vec))
mat / vec[row(mat)] # fastest
}
rowMutliply <- function(mat, vec) { # Mutliply by row
stopifnot(NROW(mat) == length(vec))
mat * vec[row(mat)] # fastest
}
row.Zscore <- function(DF) t(scale(t(DF))) # Calculate Z-score over rows of data frame.
TPM_normalize <- function(mat, SUM = 1e6) { # normalize each column to 1 million
cs = colSums(mat, na.rm = TRUE)
norm_mat = (t(t(mat) / cs)) * SUM
return(norm_mat)
}
median_normalize <- function(mat) { # normalize each column to the median of all the column-sums
cs = colSums(mat, na.rm = TRUE)
norm_mat = (t(t(mat) / cs)) * median(cs)
iprint("colMedians: ", head(signif(colMedians(norm_mat), digits = 3)))
return(norm_mat)
}
mean_normalize <- function(mat) { # normalize each column to the median of the columns
cs = colSums(mat, na.rm = TRUE)
norm_mat = (t(t(mat) / cs)) * mean(cs)
iprint("colMeans: ", head(signif(colMeans(norm_mat))))
return(norm_mat)
}
### Distance and correlation calculations --------------
eucl.dist.pairwise <- function(df2col) { # Calculate pairwise euclidean distance
dist_ = abs(df2col[,1] - df2col[,2]) / sqrt(2)
if (!is.null(rownames(df2col))) names(dist_) = rownames(df2col)
dist_
}
sign.dist.pairwise <- function(df2col) { # Calculate absolute value of the pairwise euclidean distance
dist_ = abs(df2col[,1] - df2col[,2]) / sqrt(2)
if (!is.null(rownames(df2col))) names(dist_) = rownames(df2col)
dist_
}
# Auto correlation functions
rowACF <- function(x, na_pass = na.pass, plot = FALSE, ...) { apply(x, 1, acf, na.action = na_pass, plot = plot, ...)} # RETURNS A LIST. Calculates the autocorrelation of each row of a numeric matrix / data frame.
colACF <- function(x, na_pass = na.pass, plot = FALSE, ...) { apply(x, 2, acf, na.action = na_pass, plot = plot, ...)} # RETURNS A LIST. Calculates the autocorrelation of each row of a numeric matrix / data frame.
acf.exactLag <- function(x, lag = 1, na_pass = na.pass, plot = FALSE, ... ) { # Autocorrelation with exact lag
x = acf(x, na.action = na_pass, plot = plot, ...)
x[['acf']][(lag + 1)]
}
rowACF.exactLag <- function(x, na_pass = na.pass, lag = 1, plot = FALSE, ...) { # RETURNS A Vector for the "lag" based autocorrelation. Calculates the autocorrelation of each row of a numeric matrix / data frame.
signif(apply(x, 1, acf.exactLag, lag = lag, plot = plot, ...), digits = 2)
}
colACF.exactLag <- function(x, na_pass = na.pass, lag = 1, plot = FALSE, ...) { # RETURNS A Vector for the "lag" based autocorrelation. Calculates the autocorrelation of each row of a numeric matrix / data frame.
signif(apply(x, 2, acf.exactLag, lag = lag, plot = plot, ...), digits = 2)
}
### Matrix manipulations -------------------------------------------------------------------------------------------------
rotate <- function(x, clockwise = TRUE) { # rotate a matrix 90 degrees.
if (clockwise) { t( apply(x, 2, rev)) #first reverse, then transpose, it's the same as rotate 90 degrees
} else {apply( t(x), 2, rev)} #first transpose, then reverse, it's the same as rotate -90 degrees:
}