-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil_Global.R
1819 lines (1664 loc) · 64.5 KB
/
util_Global.R
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
# Author: Ankur Shringi (ankurshringi@iisc.ac.in)
# title: util_Global.R
# subtitle: ...
# abstract: ...
# Project: util_Global
# Date created: 2019-Nov-18 12:03:40 Monday
# Enter following command to render the code as html
# `r2html()`
# Installing and Loading Packages ------------------------------------
# `install("dplyr")`
install <- function(package1, ...)
{
# convert arguments to vector
packages <- c(package1, ...)
# check if loaded and installed
loaded <- packages %in% (.packages())
names(loaded) <- packages
installed <- packages %in% rownames(installed.packages())
names(installed) <- packages
# start loop to determine if each package is installed
load_it <- function(p, loaded, installed)
{
if (loaded[p])
{
#print(paste(p, "is already loaded!"))
} else {
print(paste(p, "not loaded."))
if (installed[p]) {
print(paste(p, "is already installed!"))
suppressPackageStartupMessages(do.call("library", list(p)))
print(paste(p, "has been loaded now."))
} else {
print(paste(p, "is not installed!"))
print(paste(p, "is being installed."))
install.packages(p, dependencies = TRUE)
print(paste(p, "has been installed."))
suppressPackageStartupMessages(do.call("library", list(p)))
print(paste(p, "has been loaded now."))
}
}
}
invisible(lapply(packages, load_it, loaded, installed));
}
# Plotting two variables on different y axis -----------------------------------
# `plotyy(x, y1, y2, ...)`
plotyy <- function(x,y1,y2, # Required Arguments
y1.lim = NULL, y2.lim = NULL, # Axis limits
y1.lab = "", y2.lab = "", # All the labels
y1.legend = "", y2.legend ="", # Legends
y1.col = "red", y2.col = "blue", # Colors of the plots
y1.pch = 19, y2.pch = 22, # Pch
las=1,
...){
par(mar = c(5,4,4,5) + .1, las = 1)
# Plot 1
plot(x,y1,
ylab = y1.lab,
ylim = y1.lim,
pch = y1.pch, col = y1.col,
...)
axis(2,col = y1.col,col.axis = y1.col)
# Plot 2
par(new = TRUE)
plot(x, y2,
ylim = y2.lim,
col = y2.col, pch = y2.pch,
xaxt = "n", yaxt = "n", ylab = "",...)
axis(4)
axis(4,col = y2.col, col.axis = y2.col)
mtext(y2.lab, side = 4, line = 3, col = y2.col)
legend("topright",col = c(y1.col, y2.col), lty = 1, bty = 'n',
pch = c(y1.pch, y2.pch),
legend = c(y1.legend, y2.legend), text.col = c(y1.col, y2.col))
}
# Resetting parameters (Required when you messed up with plot parameters)---------
# `resetPar()`
resetPar <- function() {
dev.new();
par(no.readonly = TRUE);
dev.off();
}
# Plotting error bars in a basic R plot ----------------------------------------
# `plotCI(x, y = NULL, uiw, liw = uiw, ...)`
# Plotting errorbars
plotCI <- function(x, y = NULL, uiw, liw = uiw, ylim=NULL, sfrac = 0.01, add=FALSE,
col=par("col"), lwd=par("lwd"), slty=par("lty"),
xlab=deparse(substitute(x)), ylab=deparse(substitute(y)), ...) {
# from Bill Venables, R-list
if (is.list(x)) {
y <- x$y
x <- x$x
}
if (is.null(y)) {
if (is.null(x))
stop("both x and y NULL")
y <- as.numeric(x)
x <- seq(along = x)
}
ui <- y + uiw
li <- y - liw
if (is.null(ylim)) ylim <- range(c(y, ui, li), na.rm = TRUE)
if (add) {
points(x, y, col = col, lwd = lwd, ...)
} else {
plot(x, y, ylim = ylim, col = col, lwd = lwd, xlab = xlab, ylab = ylab, ...)
}
smidge <- diff(par("usr")[1:2]) * sfrac
segments(x, li, x, ui, col = col, lwd = lwd, lty = slty)
x2 <- c(x, x)
ul <- c(li, ui)
segments(x2 - smidge, ul, x2 + smidge, ul, col = col, lwd = lwd)
invisible(list(x = x, y = y))
}
# Generating reg equation for a regression -------------------------------------
# `eq.reg(reg)`
# `lm_eqn(reg)`
eq.reg <- function(reg){
rmse <- round(sqrt(mean(resid(reg)^2)), 2)
coefs <- summary(reg)$coefficients
if (dim(coefs)[1] == 2) {
b0 <- round(coefs[1],2)
b1 <- round(coefs[2],2)
r2 <- round(summary(reg)$r.squared, 2)
ar2 <- round(summary(reg)$adj.r.squared, 2)
Pvalue.slp <- round(coefs[8],3)
Pvalue.int <- round(coefs[7],3)
eqn <- bquote(italic(bold(Y)) == .(b0) ["("*p == .(Pvalue.int)*")"] +
.(b1)*italic(bold(X))["("*p == .(Pvalue.slp)*")"] * "," ~~
r^2 == .(r2) * "," ~~
adj_r^2 == .(ar2) * "," ~~ RMSE == .(rmse))
} else if (dim(coefs)[1] == 3) {
c0 <- round(coefs[1,1],2)
c1 <- round(coefs[2,1],2)
c2 <- round(coefs[3,1],2)
cr2 <- round(summary(reg)$r.squared, 2)
car2 <- round(summary(reg)$adj.r.squared, 2)
Pvalue.c0 <- round(coefs[1,4],3)
Pvalue.c1 <- round(coefs[2,4],3)
Pvalue.c2 <- round(coefs[3,4],3)
eqn <- bquote(italic(bold(Y)) == .(c0) ["("*p == .(Pvalue.c0)*")"] +
.(c1)*italic(bold(X))["("*p == .(Pvalue.c1)*")"] +
.(c2)*italic(bold(X^2))["("*p == .(Pvalue.c2)*")"]* "," ~~
r^2 == .(cr2) * "," ~~
adj_r^2 == .(car2) * "," ~~ RMSE == .(rmse))
}
}
lm_eqn <- function(reg){
coefs <- summary(reg)$coefficients
if (dim(coefs)[1] == 2) {
eq <- substitute(y == a + b %.% x*","~~italic(r)^2~"="~r2,
list(a = format(coef(reg)[[1]], digits = 2),
b = format(coef(reg)[[2]], digits = 2),
r2 = format(summary(reg)$r.squared, digits = 3)))
} else if (dim(coefs)[1] == 3) {
eq <- substitute(y == a + b %.% x+ c %.% x^2*","~~r^2~"="~r2,
list(a = format(coef(reg)[[1]], digits = 2),
b = format(coef(reg)[[2]], digits = 2),
c = format(coef(reg)[[3]], digits = 2),
r2 = format(summary(reg)$r.squared, digits = 3)))
}
#as.character(as.expression(eq));
return(eq)
}
# Plotting grey confidence bars in a base R plot -------------------------------
# `conf.bar(x, reg, alpha, varname = "")`
# Plotting grey confidence bars
# Don't use subset inside lm
# Keep same variable names in varname as in fitting dataframe
conf.bar <- function(x, reg, alpha, varname = ""){
coefs <- summary(reg)$coefficients
newx <- seq(min(x), max(x), length.out = 12)
newdata <- data.frame(newx)
if (identical(varname,"") == 1)
{
names(newdata) <- names(reg$coefficients)[2]
} else {
names(newdata) <- varname
}
# print(newdata)
# print(reg)
preds <- predict(reg, I(newdata),interval = 'confidence')
polygon(c(rev(newx), newx), c(rev(preds[ ,3]), preds[ ,2]), col = rgb(0.1,0.1,0.1,alpha), border = NA)
# model
if (dim(coefs)[1] == 2) {
abline(reg)
} else if (dim(coefs)[1] > 2) {
x.temp = seq(min(x),max(x),length.out = 100)
new = list()
new[[names(reg$coefficients)[2]]] = x.temp
lines(x.temp,predict(reg.T, newdata = new))
}
# intervals
lines(newx, preds[ ,3], lty = 'dashed', col = 'red')
lines(newx, preds[ ,2], lty = 'dashed', col = 'red')
}
# Export plots to pdf or png-----------------------------------------
# `export(filename = "test.pdf)`
export <- function(fname){
dev.copy(png,filename = paste0(fname,".png"),width = 2000, height = 1000,
antialias = "cleartype", pointsize = 16)
dev.off()
dev.copy(x11)
dev.copy2pdf(file = paste0(fname,".pdf"),width = 14, height = 9,paper = "a4r",
out.type = "pdf")
dev.off()
}
# Open and closing of pdf device ------------------------------------------
# `openPdf(pdfname = "test")`
# `closePdf(pdfname = "test")`
openPdf <- function(pdfname = "test", width = 8.3, height = 11.7, subfolder = "04-Graphics", path = getwd()) {
closeFigs()
# Opening "test.pdf"
if (!file.exists(subfolder)) {
dir.create(file.path(path, subfolder))
}
pdfname <- subfolder %/% pdfname
{pdf(paste0(pdfname, " [R].pdf"), width = width, height = height, #paper = "a4r",
onefile = T, bg = "white");
dev.control("enable")}
}
# closePdf(pdfname = "test")
closePdf <- function(pdfname = "test", subfolder = "04-Graphics"){
# Closing Images
dev.off()
# opening pdf file
system(paste0("open ", shQuote(subfolder %/% pdfname %+% " [R].pdf")))
}
# ggsave.adv ()---------------------------------------------------------------------------------------------
ggsave.adv <- function(filename = "temp",
prefix="99ZZ-99z-99",
plot = last_plot(),
asp.WbyH = 4/3,
width = 8,
height = NULL,
ext = "svg"){
install("svglite")
subfolder = "04-Graphics"
path = getwd()
if (!file.exists(subfolder)) {
dir.create(file.path(path, subfolder))
}
if ((!is.null(asp.WbyH)) + (!is.null(width)) + (!is.null(height)) == 3) {
if (asp != height/width) {
errorCondition("aspect ratio and height/weight are not equal")
}
} else if (is.null(height)) {
height = width/asp.WbyH
} else if (is.null(width)) {
width = height*asp.WbyH
} else {
errorCondition("Please provide atleast two variables among height,
width and aspect ratio")
}
for (type in ext) {
file <- prefix %+% "-" %+% filename %+% " [R]." %+% type
ggsave(filename = file, plot = plot,
width = width, height = height, unit = "cm",
path = subfolder, device = type)
}
system(paste0("open ", shQuote(subfolder %/% file)))
}
# Clear data or screen -------------------------------------------
# `clr()`
# `clr("all")`
clr <- function(mode="notall", except = NULL, env = globalenv()) {
# env <- globalenv()
ll <- ls(envir = env)
if (is.null(except)) {
except = c("clr", "clc")
} else {
except = c("clr", "clc", except)
}
ll <- ll[!ll %in% except]
if ((mode == "all") || (mode == "All")) {
rm(list = ll, envir = env)
} else if (mode == "notall") {
functions <- lsf.str(envir = env)
rm(list = setdiff(ll, functions), envir = env)}
}
# clc()
clc <- function(){cat("\014")}
# Close all open figures ------
# `closeFigs()`
closeFigs <- function() {
graphics.off()
}
# Convert any object to a string -----------------------------------------------
# `to.chr(string = objName)`
to.chr <- function(string){
as.character(substitute(string))
}
# Advance function for converting columns to numeric ---------------------------
# `as.numeric.adv(x)`
as.numeric.adv <- function(x) {
if (class(x) == "factor") {
as.numeric(levels(x))[x]
} else {
as.numeric(x)
}
}
# Converting a data frame column to numeric ------
col2num <- function(df,column, use.names = FALSE){
unlist(df[column], use.names = use.names)
}
# Converting classes of columns of data frame -----------------------------------
# `convertClass(obj = df, types = to.chr(fnin - fnic))`
convertClass <- function(obj, types, date.origin = "1970-01-01"){
# Input data is pure dataframe
# Check you give the classes in lowerclass
# It works for all columns
if (class(obj)[1] != "data.frame") {
# in case obj is tbl_df or tbl
obj <- as.data.frame(obj)
}
if (is.character(types)) {
types <- types %>%
gsub(.,pattern = ",", replacement = "") %>%
gsub(.,pattern = " ", replacement = "") %>%
gsub(.,pattern = "-", replacement = "") %>%
strsplit(.,"") %>% unlist(.)
}
origin <- date.origin
as.date <- function(x){
if (class(x) == "factor") {
as.Date(x, origin = origin)
} else {
as.Date(as.numeric.adv(x), origin = origin)
}}
out <- lapply(1:length(obj),
FUN = function(i){FUN1 <- switch(tolower(types[i]),
character = as.character,
c = as.character,
numeric = as.numeric.adv,
n = as.numeric.adv,
integer = as.integer,
i = as.integer,
factor = as.factor,
f = as.factor,
date = as.date,
d = as.date,
logical = as.logical,
l = as.logical); FUN1(obj[,i])})
names(out) <- colnames(obj)
return(as.data.frame(out, stringsAsFactors = FALSE, check.names = FALSE))
}
# Generating unique file names -------------------------------------------------
# `uniqueFilename(filename = "test.pdf", default = FALSE)`
#tempfile
uniqueFilename <- function(filename, default = FALSE){
sysTime <- format(Sys.time(), format = "%y-%b-%d-%H%M%S")
if (default == TRUE) {
return(sysTime %+% '-' %+% filename)
}else{
return(filename %+% '-' %+% sysTime)
}
}
# Sandeep: Borrowed Functions
# From Sandeep
# Extracting different summary of linear model ---------------------------------
# `summaryLM(reg)`
summaryLM <- function(reg){
out = {}
out$Slope <- coef(reg)[2]
out$Intercept <- coef(reg)[1]
out$Slope25 <- confint(reg)[2,"2.5 %"]
out$Slope95 <- confint(reg)[2,"97.5 %"]
out$Intercept25 <- confint(reg)[1,"2.5 %"]
out$Intercept95 <- confint(reg)[1,"97.5 %"]
out$SlopePval <- summary(reg)$coefficients[2,"Pr(>|t|)"]
out$InterceptPval <- summary(reg)$coefficients[1,"Pr(>|t|)"]
out$RSquared <- summary(reg)$r.squared
out$AdjRSquared <- summary(reg)$adj.r.squared
return(out)
}
# Count occurrence of a character in a string -----------------------------
# `char.count (string = "string", Char = "i")`
char.count <- function(string, Char ="."){
return(length(unlist(strsplit(string, Char, fixed = TRUE))) - 1)
}
# Add Path to file name ----------------------------------------------------
# `getwd()`
"%/%" = function(path, file) {
if (substr(file, 1, 1) == "/") {
file = substr(file, 2, nchar(file))
}
if (substr(file, nchar(file), nchar(file)) == "/" ) {
file = substr(file, 1, nchar(file) - 1 )
}
if (substr(path, nchar(path), nchar(path)) != "/" ) {
path = paste0(path, "/")
}
return(paste0(path, file ))
}
# Not in the list ----------------------------------------------------
# `getwd()`
"%!in%" = function(x,y)!('%in%'(x,y))
# Save data as csv file (no need to worry about path and extension) ------------
# `write.csv.adv (data, file.name, path = getwd(), subfolder = "Output-Tables" )`
write_csv.adv <- function(data, file.name, path = getwd(),
subfolder = "03-Tables", quote = "none", fun_family = "csv", ... ){
install("readr")
# if subfolder doesn't exist then create it.
if (!file.exists(subfolder)) {
dir.create(file.path(path, subfolder))
}
# In case my file name already have .csv in it
# we don't wan't to add another .csv
if (substr(file.name, nchar(file.name) - 3, nchar(file.name)) != ".csv") {
file = paste0(file.name, ".csv")
} else {
file = gsub("(.csv)+$", ".csv", file.name)
}
if (fun_family == "csv") {
write_csv(x = data, file = path %/% subfolder %/% file, quote = quote, ... )
} else if (fun_family == "csv2") {
write_csv2(x = data, file = path %/% subfolder %/% file, quote = quote, ... )
} else if (fun_family == "excel_csv") {
write_excel_csv(x = data, file = path %/% subfolder %/% file, quote = quote, ... )
} else if (fun_family == "excel_csv2") {
write_excel_csv2(x = data, file = path %/% subfolder %/% file, quote = quote, ... )
} else {
stop("Please provide fun_family parameter from 'csv', `csv2`, `excel_csv`, `excel_csv2` only!")
}
}
# Saving session info to a txt file --------------------------------------------
# `runInfo()`
runInfo <- function(time=FALSE){
closeAllConnections()
fileName <- file(basename(getwd()) %+% "-Session Info.txt")
sink(fileName)
if (time == TRUE) {
msg <- "Ran by " %+% getUser() %+% " on " %+%
as.character(Sys.time()) %+% "\n"
} else {
msg <- "Ran by " %+% getUser() %+% " on " %+%
as.character(Sys.Date()) %+% "\n"
}
catn(msg)
catn(capture.output(sessionInfo(),split = TRUE))
sink()
closeAllConnections()
}
# Get User Name -----------------------------------------------------------
# `getUser()`
getUser <- function() {
env <- if (.Platform$OS.type == "windows") "USERNAME" else "USER"
unname(Sys.getenv(env))
}
# Publication Theme for ggplot2 -------------------------------------------
# `theme_publication(base_size=14, base_family="")`
# `scale_fill_Publication()`
# `scale_colour_Publication`
theme_Publication <- function(base_size=14, base_family="") {
install("grid")
install("ggthemes")
(theme_foundation(base_size = base_size, base_family = base_family) +
theme(plot.title = element_text(face = "bold",
size = rel(1.2), hjust = 0.5),
text = element_text(),
panel.background = element_rect(colour = NA),
plot.background = element_rect(colour = NA),
panel.border = element_rect(colour = NA),
axis.title = element_text(face = "bold",size = rel(1)),
axis.title.y = element_text(angle = 90, vjust = 2),
axis.title.x = element_text(vjust = -0.2),
axis.text = element_text(),
axis.line.x = element_line(colour = "black",size = 1),
axis.line.y = element_line(colour = "black",size = 1),
axis.ticks = element_line(),
panel.grid.major = element_line(colour = "#f0f0f0"),
panel.grid.minor = element_blank(),
legend.key = element_rect(colour = NA),
legend.position = "bottom",
legend.direction = "horizontal",
legend.key.size = unit(0.2, "cm"),
legend.margin = unit(0, "cm"),
legend.title = element_text(face = "bold"),
plot.margin = unit(c(10,5,5,5),"mm"),
strip.background = element_rect(colour = "#f0f0f0",fill = "#f0f0f0"),
strip.text = element_text(face = "bold")
))
}
# scale_fill_Publication()
scale_fill_Publication <- function(...){
install("scales")
discrete_scale("fill","Publication",manual_pal(values = c("#386cb0","#fdb462","#7fc97f","#ef3b2c","#662506","#a6cee3","#fb9a99","#984ea3","#ffff33")), ...)
}
# scale_colour_Publication()
scale_colour_Publication <- function(...){
install("scales")
discrete_scale("colour","Publication",manual_pal(values = c("#386cb0","#fdb462","#7fc97f","#ef3b2c","#662506","#a6cee3","#fb9a99","#984ea3","#ffff33")), ...)
}
# Reset Everything (Like a new R session) --------------------------------------
# `reset()`
reset <- function(){
clr()
clc()
closeFigs()
invisible(resetPar())
}
# Concatenate object as Text -------------------------------------------
# `"a" %+% "b"`
"%+%" = function(obj_1, obj_2) {
paste(obj_1, obj_2, sep = "")
}
# cat() that appends a newline ---------------------------------------
# `catn(..., file = "", sep = " ", fill = FALSE, labels = NULL, append = FALSE)`
catn = function(..., file = "", sep = " ", fill = FALSE, labels = NULL,
append = FALSE, console = TRUE, color = NULL,
newline = TRUE) {
if (newline) {
n = '\n'
} else {
n = ""
}
if (console) {
if (!is.null(color)) {
install("crayon")
eval(expr = parse(text = "cat(" %+% color %+% "(" %+% quote(...) %+% "),'" %+% n %+% "')"))
} else (
cat(..., n, file = file, sep = sep, fill = fill, labels = labels,
append = append)
)
}
if (file != "") {
cat(..., n, file = file, sep = sep, fill = fill, labels = labels,
append = append)
}
}
# List objects available in the environment-------------------------------------
# `list.objects(env = .GlobalEnv)`
list.objects <- function(env = .GlobalEnv){
if (!is.environment(env)) {
env <- deparse(substitute(env))
stop(sprintf('"%s" must be an environment', env))
}
obj.type <- function(x) class(get(x, envir = env))
foo <- sapply(ls(envir = env), obj.type)
object.name <- names(foo)
names(foo) <- seq(length(foo))
dd <- data.frame(CLASS = foo, OBJECT = object.name,
stringsAsFactors = FALSE)
dd[order(dd$CLASS),]
}
# Check whether all the elements are same or identical -------------------------
# `all.same(vector)`
# `all.identical(x, warn = FALSE)`
#
# usage
# all.same(c(1,1,NA))
# all.same(c(1,1,NA), na.rm = TRUE)
# all.same(c(NA, NA, NA), na.rm = TRUE, all.na.as = TRUE)
# all.same(c(NA, NA ,NA), na.rm = FALSE)
all.same = function(vector, na.rm = FALSE, all.na.as = NA){
# Give a vector of values and it will tell whether all the values are same or not
# Returns boolean results in terms of True or False
if (!na.rm) {
if (length(unique(vector)) == 1) {
if (is.na(unique(vector))) {
return(all.na.as)
} else {
return(TRUE)
}
} else {
return(FALSE)
}
} else {
vector <- vector[!is.na(vector)]
if (length(vector) == 0){
return(all.na.as)
} else if (length(unique(vector)) == 1) {
return(TRUE)
} else {
return(FALSE)
}
}
}
# all.identical(x, warn = FALSE)
all.identical <- function(x, warn = FALSE) {
if (length(x) == 1L) {
if (warn) {
warning("'x' has a length of only 1")
}
return(TRUE)
} else if (length(x) == 0L) {
warning("'x' has a length of 0")
return(logical(0))
} else {
TF <- vapply(1:(length(x) - 1),
function(n) identical(x[[n]], x[[n + 1]]),
logical(1))
if (all(TF)) TRUE else FALSE
}
}
# Stitch (Collapse a vector of strings) ------------------------------------
# `stich(vec, collapse = " ")`
stitch <- function(vec, collapse = " "){
paste0(as.character(vec), collapse = collapse)
}
# Remove na from a vector -------------------------------------------------
# `rm.na(vec)`
rm.na <- function(vec){
return(vec[!is.na(vec)])
}
# Merging two data frame like mean +- sd -----------------------------------
# `fuse(df.prfx, df.sufx, merged.Cols , link = "±")`
fuse <- function(df.prfx, df.sufx, merged.Cols , link = "±"){
# Checking no. of cols are identical
if (dim(df.prfx)[2] != dim(df.sufx)[2]) {
stop("Number of columns are not matching, please recheck")
}
if (dim(df.prfx)[1] != dim(df.sufx)[1]) {
print.warn("Please note that number of rows are not matching!")
}
if (!identical(sort(names(df.prfx)),sort(names(df.sufx)))) {
stop("Columns names are not matching, please fix")
}
# Merging matrix
merged <- merge(df.prfx, df.sufx, by = merged.Cols, all = TRUE,
suffixes = c(".prfx",".sufx"))
out <- as.data.frame(matrix(NA, nrow = dim(merged)[1], ncol = dim(df.prfx)[2] ))
names(out) <- names(df.prfx)
out[, merged.Cols] <- merged[ , merged.Cols]
to.fuse.cols <- setdiff(names(df.prfx),merged.Cols)
for (cols in to.fuse.cols) {
prfx.rows.blank <- merged[,cols %+% ".prfx"] %in% c(""," ")
prfx.rows.Na <- is.na(merged[,cols %+% ".prfx"])
prfx.rows.valid <- (!prfx.rows.blank & !prfx.rows.Na)
sufx.rows.blank <- merged[,cols %+% ".sufx"] %in% c(""," ")
sufx.rows.Na <- is.na(merged[,cols %+% ".sufx"])
sufx.rows.valid <- (!sufx.rows.blank & !sufx.rows.Na)
# Completely valid rows
rows.valid <- prfx.rows.valid & sufx.rows.valid
out[rows.valid, cols] <- paste(merged[rows.valid ,cols %+% ".prfx"],
merged[rows.valid ,cols %+% ".sufx"],
sep = " " %+% link %+% " ")
# Only prefix valid rows
only.prfx.rows.valid <- prfx.rows.valid & !sufx.rows.valid
out[only.prfx.rows.valid, cols] <- merged[only.prfx.rows.valid, cols %+% ".prfx"]
# Only sufix valid rows
only.sufx.rows.valid <- sufx.rows.valid & !prfx.rows.valid
if (sum(only.sufx.rows.valid) > 0) {
out[only.sufx.rows.valid, cols] <- merged[only.sufx.rows.valid, cols %+% ".sufx"]
print.warn("Watch out suffix df have valid rows while prefix df not!!")
}
rows.rest <- !(prfx.rows.valid | sufx.rows.valid)
out[rows.rest, cols] <- ""
}
return(out)
}
# Moving Average & Standard Deviations ------------------------------------
# `mov.avg(x, width, align = "center", partial = FALSE, na.rm = FALSE )`
mov.avg <- function(x, width, align = "center", partial = FALSE, na.rm = FALSE ) {
# Installing zoo
install("zoo")
out <- rollapply(data = x, width = width, FUN = mean, na.rm = na.rm, align = align, fill = NA, partial = partial)
return(out)
}
# `mov.sd(x, width, align = "center", partial = FALSE, na.rm = FALSE )`
mov.sd <- function(x, width, align = "center", partial = FALSE) {
install("zoo")
out <- rollapply(data = x, width = width, FUN = sd, na.rm = na.rm, align = align, fill = NA, partial = partial)
return(out)
}
# Open Current Directory directly from R ---------------------------------------
# 'openwd()'
openwd <- function(dir = getwd()){
if (.Platform['OS.type'] == "windows") {
shell.exec(dir)
} else {
system(paste(Sys.getenv("R_BROWSER"), dir))}
}
# List objects by their size ----------------------------------------------
# `lsos()`
.ls.objects <- function(pos = 1, pattern, order.by,
decreasing = FALSE, head = FALSE, n = 5) {
napply <- function(names, fn) sapply(names, function(x)
fn(get(x, pos = pos)))
names <- ls(pos = pos, pattern = pattern)
obj.class <- napply(names, function(x) as.character(class(x))[1])
obj.mode <- napply(names, mode)
obj.type <- ifelse(is.na(obj.class), obj.mode, obj.class)
obj.prettysize <- napply(names, function(x) {
capture.output(print(object.size(x), units = "auto")) })
obj.size <- napply(names, object.size)
obj.dim <- t(napply(names, function(x)
as.numeric(dim(x))[1:2]))
vec <- is.na(obj.dim)[, 1] & (obj.type != "function")
obj.dim[vec, 1] <- napply(names, length)[vec]
out <- data.frame(obj.type, obj.size, obj.prettysize, obj.dim)
names(out) <- c("Type", "Size", "PrettySize", "Rows", "Columns")
if (!missing(order.by))
out <- out[order(out[[order.by]], decreasing = decreasing), ]
if (head)
out <- head(out, n)
out
}
lsos <- function(..., n=10) {
.ls.objects(..., order.by = "Size", decreasing = TRUE, head = TRUE, n = n)
}
# function to see logs/ diary of work and project progress ------
diary <- function(dir = "C:/Users/Ankur/OneDrive - Indian Institute of Science/Work",
filename = "[Diary].xlsm",
highlight_proj = "Growth"){
#Installing necessary plugins
install(c("tidyverse", "DT", "readxl", "htmlwidgets"))
#Name and path for the file
table <- read_excel(dir %/% filename,
sheet = "Work_Diary") %>%
mutate(`#` = as.integer(`#`),
Project = as.factor(Project),
Section = as.factor(Section),
File = as.factor(File),
Task_Type = as.factor(Task_Type))
# Creating html table
widget <- datatable(table,
class = 'display',
filter = list(position = 'top', clear = TRUE, plain = FALSE),
extensions = c('FixedHeader', "KeyTable", "Buttons"),
plugins = "ellipsis",
escape = TRUE,
options = list(paging = TRUE,
searchHighlight = TRUE,
search = list(smart = TRUE),
pageLength = 400,
autoWidth = TRUE,
fixedHeader = TRUE,
keys = TRUE, # Keytable
dom = 'lBfrtip',
buttons = I('colvis'),
columnDefs = list(list(width = '100%',
targets = "_all",
className = 'hower'),
list(targets = "_all",
render = JS("$.fn.dataTable.render.ellipsis(50, false )"))))) %>%
DT::formatDate(2, "toLocaleString") %>%
DT::formatStyle(columns = colnames(table), `font-size` = '100%', `width` = "100%")
# Saving html table in the same folder as html file
DT::saveWidget(widget, dir %/% filename %+% '.html', selfcontained = TRUE)
# opening the file
browseURL(dir %/% filename %+% '.html')
#https://datatables.net/manual/styling/classes
}
# blank as NA ------
#Usage: data %>% mutate_each(funs(blank2NA))
blank2NA <- function(x){
install("dplyr")
if ("factor" %in% class(x)) x <- as.character(x) # since ifelse wont work with factors
ifelse(as.character(x) != "", x, NA)
}
# as.attrib.same ----------------------------------------------------------
# 'Usage: 'is.attrib.same(df = ha_11, by_col = "tag", attrib_cols = c("plot_id","year","qdt","s.qdt","gx","gy","spp","date4"))'
# print.warn ------
print.warn = function(msg) {
# Taken from sandeep's util.r file
# Signals a test failure.
# msg - Message to be printed.
catn(msg)
warning(msg, call. = F)
}
# fix.levels------
fix.levels = function(x, level_map) {
# Taken from sandeep's util.r file
# "Re-levels" factors in 'x' to correspond to the levels in 'level_map'.
# x - Vector of factors, possibly with fewer levels than 'level_map.'
# level_map - Vector of named unique levels.
# return - Releveled 'x.'
return(factor(level_map[levels(x)[x]], level_map, names(level_map)))
}
# sum.adv ------
# Modified sum function to handle values like all NA
sum.adv <- function(x){
if (sum(!is.na(x)) == 0) {
out <- NA
} else {
out <- sum(x, na.rm = TRUE)
}
return(out)
}
# max.adv ------
# Modified max function to handle values like all NA
max.adv <- function(x){
if (sum(!is.na(x)) == 0) {
out <- NA
} else {
out <- max(x, na.rm = TRUE)
}
return(out)
}
# max.adv ------
# Modified min function to handle values like all NA
min.adv <- function(x){
if (sum(!is.na(x)) == 0) {
out <- NA
} else {
out <- min(x, na.rm = TRUE)
}
return(out)
}
# stat.summary------
# stat.summary
# given a data frame, a table of list of variables and its filter, and list of grouping variables it provides a mean, standard deviation and other relavant summaries.
# Example usage
# data("iris")
# table <- data.frame(var = names(iris)[-dim(iris)[2]], filter = NA)
# stat.summary(colTable = table, group_var = "Species",df_in = iris)
# out_w <- stat.summary(colTable = table, group_var = "Species", df_in = iris, format = "wide")
# out_l <- stat.summary(colTable = names(iris)[1:4], group_var = "Species", df_in = iris, format = "long")
# out_list <- stat.summary(colTable = table, group_var = "Species", df_in = iris, format = "list")
#
stat.summary <- function(colTable, group_var, df_in, format = "wide"){
list_df <- list()
class = class(colTable)
summary.vars <- c("mean", "sd", "cv", "max", "min", "n", "se")
n.sum.vars <- length(summary.vars)
n.gr.vars <- length(group_var)
if ("data.frame" %!in% class) {
if (class == "character") {
colTable = data.frame(var = colTable, filter = NA)
} else {
stop("Check the class of the colTable variable! \n
It should be eithe character vector of variables names \n
or \n
a data.frame of variable names and associated filter columns.")
}
}
for (f in (1:dim(colTable)[1])) {
var.name <- colTable[f, 1]
filter.var <- colTable[f, 2]
filter.var.name <- filter.var
if (is.na(filter.var) == TRUE) {
filter.var = TRUE
}
if (format == "wide") {
var.mean <- var.name %+% ".mean"
var.sd <- var.name %+% ".sd"
var.cv <- var.name %+% ".cv"
var.max <- var.name %+% ".max"
var.min <- var.name %+% ".min"
var.n <- var.name %+% ".n"
var.se <- var.name %+% ".se"
} else if (format %in% c("long", "list")) {
var.mean <- "mean"
var.sd <- "sd"
var.cv <- "cv"
var.max <- "max"
var.min <- "min"
var.n <- "n"
var.se <- "se"
} else {
print(format)
stop("Please check the format! Default is `wide`, other is `long` ")
}
var <- colTable[f, 1] %+% "[" %+% filter.var %+% " == TRUE]"
formula.mean <- "mean(" %+% var %+% ", na.rm = TRUE)"
formula.sd <- "sd(" %+% var %+% ", na.rm = TRUE)"
formula.cv <- var.sd %+% "*100/" %/% var.mean
formula.max <- "max.adv(" %+% var %+% ")"
formula.min <- "min.adv(" %+% var %+% ")"
formula.n <- "sum.adv(!is.na(" %+% var %+% "))"
formula.se <- var.sd %+% "/sqrt(" %+% var.n %+% ")"
list_df[[var.name]] <- df_in %>% group_by_at(vars(group_var)) %>%
summarise(!!var.mean := eval(parse(text = formula.mean)),
!!var.sd := eval(parse(text = formula.sd)),
!!var.cv := eval(parse(text = formula.cv)),
!!var.min := eval(parse(text = formula.min)),
!!var.max := eval(parse(text = formula.max)),
!!var.n := eval(parse(text = formula.n)),
!!var.se := eval(parse(text = formula.se))) %>%
mutate(var = var.name,
filter.var = filter.var.name)
}
if (format == "wide") {
out <- list_df %>%
reduce(left_join, by = group_var) %>%
as.data.frame() %>%
select(-starts_with("var"),-starts_with("filter.var"))
} else if (format == "long") {
out <- list_df %>%
reduce(bind_rows) %>%
as.data.frame() %>%
select(1:length(n.gr.vars),
n.sum.vars + n.gr.vars + 1, n.sum.vars + n.gr.vars + 2,
(n.gr.vars + 1):(n.gr.vars + n.sum.vars))
} else if (format == "list") {
out = list_df
} else {
stop("Please check the format! Default is `wide`, other is `long` ")
}
return(out)
}
# pad.00------
# Pads a number or string with zeros
pad.00 <- function(string, width = 2, side = "left"){
warning("pad.00 is deprecated. Please use pad_decimal() instead.")
install("stringr")
str_pad(string = string, width = width, side = side, pad = "0")
}
# pad_decimal------
# Pads a number or string with characters on left or right side.
# Usage
# pad_decimal(3.14, 3, 4, " ", "0")
pad_decimal <- function(x, width_left = 0, width_right = 2, char_left = " ", char_right = "0") {
# x: input decimal number
# width_left: desired width left side (excluding decimal point)
# width_right: desired number of padding digits on the right side
# char_left: padding character for the left side
# char_right: padding character for the right side
# split the number into integer and fractional parts
int_part <- floor(x)
frac_part <- x - int_part
install("stringr")
# convert the integer part to a character string and pad with specified character from left
int_str <- stringr::str_pad(string = int_part, width = width_left, side = "left", pad = char_left)
# convert the fractional part to a character string and pad with specified character from right
frac_str <- formatC(round(frac_part, n), digits = n, format = "f")