-
Notifications
You must be signed in to change notification settings - Fork 0
/
util_Global.h.R
1186 lines (1100 loc) · 44.8 KB
/
util_Global.h.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
#' ---
#' title: util_Global.R
#' author: "Author: Ankur Shringi ([email protected]) <br>
#' Project: Utilities <br><br> Enter Following command to execute it. <br>
#' `rmarkdown::render('c:/Users/Ankur/hubiC/Work/Projects/Utilities/util_Global/util_Global.R', clean = TRUE, quiet = TRUE)` <br><br>
#' Date: 2015"
#' output:
#' html_document:
#' toc: true
#' number_sections: true
#' highlight: kate #zenburn
#' ---
#' <a href="#top"> Go back to the Table of Contents </a>
# Ankur: Utitlity functions
# Installing and Loading Packages ------------------------------------
#' # Installing and loading packages <br> `install("dplyr")`
#' <a href="#top"> Go back to the Table of Contents </a>
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 varibales on different y axis -----------------------------------
#' # Plotting two varibales on different y axis <br> `plotyy(x, y1, y2, ...)`
#' <a href="#top"> Go back to the Table of Contents </a>
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))
}
# Reseting parametes (Required when you messed up with plot parameters)---------
#' # Reseting parametes (Required when you messed up with plot parameters) <br> `resetPar()`
#' <a href="#top"> Go back to the Table of Contents </a>
#fResetPar
resetPar <- function() {
dev.new();
par(no.readonly = TRUE);
dev.off();
#op
}
# Plotting error bars in a basic R plot ----------------------------------------
#' # Plotting error bars in a basic R plot <br> `plotCI(x, y = NULL, uiw, liw = uiw, ...)`
#' <a href="#top"> Go back to the Table of Contents </a>
# 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 -------------------------------------
#' # Generating reg equation for a regression <br> `eq.reg(reg)` <br> `lm_eqn(reg)`
#' <a href="#top"> Go back to the Table of Contents </a>
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(italic(y) == a + b %.% italic(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(italic(y) == a + b %.% italic(x)+ c %.% italic(x^2)*","~~italic(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));
}
# Plotting grey confidence bars in a base R plot -------------------------------
#' # Plotting grey confidence bars in a base R plot <br> `conf.bar(x, reg, alpha, varname = "")`
#' <a href="#top"> Go back to the Table of Contents </a>
# 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 plots to pdf or png <br> `export(filename = "test.pdf)`
#' <a href="#top"> Go back to the Table of Contents </a>
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()
}
# Opne and closing of pdf device ------------------------------------------
#' # Opne and closing of pdf device <br> `openPdf(pdfname = "test")` <br> `closePdf(pdfname = "test")`
#' <a href="#top"> Go back to the Table of Contents </a>
openPdf <- function(pdfname = "test", width = 14, height = 9, subfolder = "Output-R-Graphics", path = getwd()){
closeFigs()
# Opening "test.pdf"
if (!file.exists(subfolder)) {
dir.create(file.path(path, subfolder))
}
pdfname <- subfolder %/% pdfname
{pdf(paste0(pdfname, ".pdf"), width = width, height = height, paper = "a4r",
onefile = T, bg = "white");
dev.control("enable")}
}
# closePdf(pdfname = "test")
closePdf <- function(pdfname = "test", subfolder = "Output-R-Graphics"){
# Closing Images
dev.off()
# opening pdf file
system(paste0("open ", shQuote(subfolder %/% pdfname), ".pdf"))
}
# Clear data or screen -------------------------------------------
#' # Clear data or screen <br> `clr()` <br> `clr("all")`
#' <a href="#top"> Go back to the Table of Contents </a>
clr <- function(mode="notall"){
ENV <- globalenv()
ll <- ls(envir = ENV)
if ((mode == "all") || (mode == "All")) {
ll <- ll[!ll %in% c("clr","clc")]
rm(list = ll, envir = ENV)
}else if (mode == "notall") {
rm(list = setdiff(ls(envir = ENV), lsf.str(envir = ENV)), envir = ENV)}
}
# clc()
clc <- function(){cat("\014")}
# Close all open figures ------
#' # Close all open figures <br> `closeFigs()`
#' <a href="#top"> Go back to the Table of Contents </a>
closeFigs <- function(){
graphics.off()
}
# Convert any object to a string -----------------------------------------------
#' # Convert any object to a string <br> `to.chr(string = objName)`
#' <a href="#top"> Go back to the Table of Contents </a>
to.chr <- function(string){
as.character(substitute(string))
}
# Advance function for converting columns to numeric ---------------------------
#' # Advance function for converting columns to numeric <br> `as.numeric.adv(x)`
#' <a href="#top"> Go back to the Table of Contents </a>
as.numeric.adv <- function(x) {
if (class(x) == "factor") {#+ echo = FALSE
as.numeric(levels(x))[x]
}else{
as.numeric(x)
}
}
#+ echo = FALSE
# Converting a dataframe column to numeric ------
#' ## Converting a dataframe column to numeric
col2num <- function(df,column, use.names = FALSE){
unlist(df[column], use.names = use.names)
}
# Converting classes of columns of dataframe -----------------------------------
#' # Converting classes of columns of dataframe <br> `convertClass(obj = df, types = to.chr(fnin - fnic))`
#' <a href="#top"> Go back to the Table of Contents </a>
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){
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 -------------------------------------------------
#' # Generating unique file names <br> `uniqueFilename(filename = "test.pdf", default = FALSE)`
#' <a href="#top"> Go back to the Table of Contents </a>
#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 ---------------------------------
#' # Extracting different summary of linear model <br> `summaryLM(reg)`
#' <a href="#top"> Go back to the Table of Contents </a>
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 occurance of a character in a string -----------------------------
#' # Count occurance of a character in a string <br> `char.count (string = "string", Char = "i")`
#' <a href="#top"> Go back to the Table of Contents </a>
char.count <- function(string, Char ="."){
return(length(unlist(strsplit(string, Char, fixed = TRUE))) - 1)
}
# Add Path to filename ----------------------------------------------------
#' # Add path to filename <br> `getwd()`
#' <a href="#top"> Go back to the Table of Contents </a>
"%/%" = function(Path.Folder.Data,File.Name){
# Cheking whether / was already added to path
if (substr(Path.Folder.Data,nchar(Path.Folder.Data),nchar(Path.Folder.Data)) == "/") {
File.Name <- paste0(Path.Folder.Data, File.Name)
}else{
File.Name <- paste0(Path.Folder.Data, "/", File.Name)
}
return(File.Name)
}
# Not in the list ----------------------------------------------------
#' # Not in the list <br> `getwd()`
#' <a href="#top"> Go back to the Table of Contents </a>
"%!in%" = function(x,y)!('%in%'(x,y))
# Save data as csv file (no need to worry about path and extension) ------------
#' # Save data as csv file (no need to worry about path and extension) <br> `save.csv(data, file.name, path = getwd(), subfolder = "Output-R-Tables" )`
#' <a href="#top"> Go back to the Table of Contents </a>
save.csv <- function(data,file.name,path=getwd(), row.Names = FALSE,
subfolder="Output-Tables"){
# In case my path has forward slash
if (substr(path,nchar(path),nchar(path)) != "/") {
path <- paste0(path,"/")
}
# if subfolder doesn't exist then create it.
if (!file.exists(subfolder)) {
dir.create(file.path(path, subfolder))
}
path <- path %/% subfolder
char = "."
# In case my file name already have .csv in it
# we don't wan't to add another .csv
if (char.count(file.name) == 0) {
file.name <- path %/% file.name %+% ".csv"
}else if (char.count(file.name) == 1) {
file.name <- path %/% file.name
}else if (char.count(file.name) == 2) { # Checking whether we have >1 "."
last.ext <- rev(unlist(strsplit(file.name,char,fixed = TRUE)))[1]
second.last.ext <- rev(unlist(strsplit(file.name,char,fixed = TRUE)))[2]
if (last.ext == second.last.ext) {
file.name <- paste(unlist(strsplit(file.name,char,fixed = TRUE))[1:2],
collapse = ".")
}else{
warning(paste0("File name <", file.name,
"> has muliple '.' other than extention"))
}
}else{
if (unique(rev(unlist(strsplit(file.name,char,fixed = TRUE)))[1:3]) == "csv") {
stop(paste0("File name <", file.name, "> has muliple '.' other than extention"))
}
}
write.csv(data,file.name,row.names = row.Names)
}
# Saving session info to a txt file --------------------------------------------
#' # Saving session info to a txt file <br> `runInfo()`
#' <a href="#top"> Go back to the Table of Contents </a>
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 -----------------------------------------------------------
#' # Get User Name <br> `getUser()`
#' <a href="#top"> Go back to the Table of Contents </a>
getUser <- function()
{
env <- if (.Platform$OS.type == "windows") "USERNAME" else "USER"
unname(Sys.getenv(env))
}
# Header to append to any new R file -------------------------------------------
#' # Header to append to any new R file <br> `header()`
#' <a href="#top"> Go back to the Table of Contents </a>
header <- function() {
file.show("C:/Users/Ankur/hubiC/Work/Projects/Utilities/util_Global/R-Header.txt")
}
# Publication Theme for ggplot2 -------------------------------------------
#' # Publication Theme for ggplot2 <br> `theme_publication(base_size=14, base_family="")` <br> `scale_fill_Publication()` <br> `scale_colour_Publication`
#' <a href="#top"> Go back to the Table of Contents </a>
install(c("ggthemes","grid"))
theme_Publication <- function(base_size=14, base_family="") {
library(grid)
library(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(...){
library(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(...){
library(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 Everything (Like a new R session) <br> `reset()`
#' <a href="#top"> Go back to the Table of Contents </a>
reset <- function(){
clr()
clc()
closeFigs()
invisible(resetPar())
}
# Concenate object as Text -------------------------------------------
#' # Concenate object as Text <br> `"a" %+% "b"`
#' <a href="#top"> Go back to the Table of Contents </a>
"%+%" = function(obj_1, obj_2) {
paste(obj_1, obj_2, sep = "")
}
# cat() that appends a newline ---------------------------------------
#' # cat() that appends a newline <br> `catn(..., file = "", sep = " ", fill = FALSE, labels = NULL, append = FALSE)`
#' <a href="#top"> Go back to the Table of Contents </a>
catn = function(..., file = "", sep = " ", fill = FALSE, labels = NULL,
append = FALSE) {
cat(..., "\n", file = file, sep = sep, fill = fill, labels = labels,
append = append)
}
# List objects available in the environment-------------------------------------
#' # List objects available in the environment <br> `list.objects(env = .GlobalEnv)`
#' <a href="#top"> Go back to the Table of Contents </a>
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 -------------------------
#' # Check whether all the elements are same or identical <br> `all.same(vector)` <br> `all.identical(x, warn = FALSE)`
#' <a href="#top"> Go back to the Table of Contents </a>
all.same <- function(vector){
# 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 (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
}
}
# Stich (Collapse a vector of strings) ------------------------------------
#' # Stich (Collapse a vector of strings) <br> `stich(vec, collapse = " ")`
#' <a href="#top"> Go back to the Table of Contents </a>
stich <- function(vec, collapse = " "){
paste0(as.character(vec), collapse = collapse)
}
# Remove na from a vector -------------------------------------------------
#' # Remove na from a vector <br> `rm.na(vec)`
#' <a href="#top"> Go back to the Table of Contents </a>
rm.na <- function(vec){
return(vec[!is.na(vec)])
}
# Merging two dataframe like mean +- sd -----------------------------------
#' # Merging two dataframe like mean +- sd <br> `fuse(df.prfx, df.sufx, merged.Cols , link = "±")`
#' <a href="#top"> Go back to the Table of Contents </a>
# 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 ------------------------------------
#' # Moving Average <br> `mov.avg(x, width, align = "center", partial = FALSE, na.rm = FALSE )`
#' <a href="#top"> Go back to the Table of Contents </a>
# 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)
}
#' # Moving Standard Deviations <br> `mov.sd(x, width, align = "center", partial = FALSE, na.rm = FALSE )`
#' <a href="#top"> Go back to the Table of Contents </a>
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)
}
# HTML Function -----------------------------------------------------------
#' # Various HTML Functions
#' ## `hr(0)`
install("rstudioapi")
install("devtools")
if ("roxygen2Comment" %in% rownames(installed.packages())) {
if ("roxygen2Comment" %!in% (.packages())) {
suppressPackageStartupMessages(do.call("library", list("roxygen2Comment")))}
} else {
devtools::install_github("csgillespie/roxygen2Comment")
}
hr <- function(x = 0){
if (x == 1) {
cat('<hr style="height:1px;border:none;color:#333;background-color:#333;" />')
} else if (x == 0) {
cat("<hr />")
}
}
#' ## `gototop()`
gototop <- function(x = 1){
if (x == 0) {
cat("<a href='#top'> Go back to the Table of Contents </a> ")
} else if (x == 1) {
cat('<table width="100%"> <td><hr style="height:1px;border:none;color:#333;background-color:#333;" /></td> <td style="width:1px; padding: 0 10px; white-space: nowrap;"><a href="#top"> Go back to the Table of Contents </a></td> <td><hr style="height:1px;border:none;color:#333;background-color:#333;" /></td> </table>')
}
}
# export to html
#' export2html(".R")
export2html <- function(filename, folder = 'Output-html', suppress_warnings = TRUE, browse = TRUE, output_file = NULL) {
if (suppress_warnings) {
suppressWarnings(rmarkdown::render(filename, output_dir = folder, clean = TRUE, quiet = TRUE,
output_file = output_file))
} else {
rmarkdown::render(filename, output_dir = folder, clean = TRUE, quiet = TRUE, output_file = output_file)
}
if (is.null(output_file)) {
output_file = folder %/% substr(filename, start = 1, nchar(filename) - 2)
}
if (browse) {
file_wt_ext <- folder %/% output_file
if (file.exists(file_wt_ext %+% ".html")) {
browseURL(file_wt_ext %+% ".html", getOption("browser"))
} else if (file.exists(file_wt_ext %+% ".nb.html")) {
browseURL(file_wt_ext %+% ".nb.html", getOption("browser"))
} else {
stop("Corresponding html file doesnt exists!!")
}
}
}
# Insert Code/Text as Text in Script File Automatically -------------------
#' Insert Code/Text as Text in Script File Automatically
install("rstudioapi")
i <- function(insert = c("hr","chunk","gototop","section","date")) {
insert <- match.arg(insert)
if (insert == "hr") {
rstudioapi::insertText(text = "hr() \n")
} else if (insert == "chunk") {
rstudioapi::insertText(text = "#+ results= 'asis', echo = FALSE \n")
} else if (insert == "gototop") {
rstudioapi::insertText(text = "gototop() \n")
} else if (insert == "section") {
rstudioapi::insertText(text = paste0("#+ echo = FALSE \n", "# 01 ------ \n", "#' ## \n \n", "#+ results= 'asis', echo = FALSE \n", "hr() \n"))
} else if (insert == "date") {
rstudioapi::insertText(text = format(Sys.time(), format = "%Y-%b-%d %H:%M:%S " %+% weekdays(as.Date(Sys.Date(),'%d-%m-%Y'))))
}
}
# Open Current Directory directly from R ---------------------------------------
#' # Open Current Directory directly from R <br> 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 ----------------------------------------------
#' List objects by their size <br> `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)
}
#+ echo = FALSE
# function to see logs/ diary of work and project progress ------
#' # function to see logs/ diary of work and project progress
diary <- function(){
#' Installing necessary plugins
install(c("dplyr","DT","readxl","htmlwidgets"))
#' Name and path for the file
dir <- "c:/Users/Ankur/hubiC/Work/Projects/"
name <- "Diary&Tasks[Ankur]"
table <- read_excel(dir %/% name %+% ".xlsm",sheet = "Work_Diary")
#` Converting classes
table$`#` <- as.integer(table$`#`)
table$`Project` <- as.factor(table$`Project`)
table$Section <- as.factor(table$Section)
table$`Context File` <- as.factor(table$`Context Files`)
table$`Task Type` <- as.factor(table$`Task_Type`)
#' Creating html table
widget <- datatable(table, class = 'display', filter = list(position = 'top', clear = TRUE, plain = FALSE),
extensions = 'FixedHeader', escape = TRUE,
options = list(initComplete = JS("function(settings, json) {",
"$(this.api().table().header()).css({'background-color': '#000', 'color': '#fff'});",
"}"),
paging = TRUE, searchHighlight = TRUE,search = list(smart = TRUE),pageLength = 400,
autoWidth = TRUE, fixedHeader = TRUE,
columnDefs = list(list(width = '100%', targets = "_all",
className = 'compact')))) %>%
formatStyle('Project',target = "row", backgroundColor = styleEqual(c("Growth"), c('yellow'))
)
#' Saving html table in the same folder as html file
DT::saveWidget(widget, dir %/% name %+% '.html',selfcontained = TRUE)
#' opening the file
browseURL(dir %/% name %+% '.html')
#https://datatables.net/manual/styling/classes
}
#+ echo = FALSE
# blank as NA ------
#' ## 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)
}
#+ results= 'asis', echo = FALSE
hr()
# as.attrib.same ----------------------------------------------------------
#' ## 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"))
#+ results= 'asis', echo = FALSE
hr()
# print.warn ------
#' ## 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)
}
#+ results= 'asis', echo = FALSE
hr()
#+ echo = FALSE
# fix.levels------
#' ## 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)))
}
#+ results= 'asis', echo = FALSE
hr()
#+ echo = FALSE
## rename.col.variable.to ------
#' ## Renaming variable while melting the data
rename.col.variable.to <- function(df,
old.var.name = "variable",
new.var.name = "variable") {
names(df)[names(df) == old.var.name] <- new.var.name
return(df)
}
#+ results= 'asis', echo = FALSE
hr()
#+ echo = FALSE
#+ echo = FALSE
## 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)
}
#+ results= 'asis', echo = FALSE
sink("NULL")
xxxx <- hr()
sink(xxxx); rm(xxxx)
# 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)
}
#+ results= 'asis', echo = FALSE
sink("NULL")
xxxx <- hr()
sink(xxxx); rm(xxxx)
# 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)
}
#+ results= 'asis', echo = FALSE
sink("NULL")
xxxx <- hr()
sink(xxxx); rm(xxxx)
# 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.
stat.summary <- function(colTable, group_var, df_in){
df_out <- list()
for (f in (1:dim(colTable)[1])) {
var <- colTable[f, 1]
filter.var <- colTable[f, 2]
if (is.na(filter.var) == TRUE) {
filter.var = TRUE
}
var.mean <- var %+% ".mean"
var.sd <- var %+% ".sd"
var.cv <- var %+% ".cv"
var.max <- var %+% ".max"
var.min <- var %+% ".min"
var.n <- var %+% ".n"
var.se <- var %+% ".se"
rm(var)
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 %+% ")"
df_out[[f]] <- 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))
)
}
return(df_out %>% reduce(left_join, by = group_var) %>% as.data.frame())
}
#+ results= 'asis', echo = FALSE
sink("NULL")
xxxx <- hr()
sink(xxxx); rm(xxxx)
#+ echo = FALSE
# pad.00------
#' ## pad.00
#' Pads a number or string with zeros
pad.00 <- function(string, width = 2, side = "left"){
install("stringr")
str_pad(string = string, width = width, side = side, pad = "0")
}
#+ results= 'asis', echo = FALSE
sink("NULL")
xxxx <- hr()
sink(xxxx); rm(xxxx)
# is.attrib.same ---------------
#' Crosscheck whether two data sets are same in some columns
#' Checks the internal consistency of the data by a particular column