-
Notifications
You must be signed in to change notification settings - Fork 8
/
utilsRS.r
4199 lines (3192 loc) · 135 KB
/
utilsRS.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
#------------------------------------------------------#
# THESE ARE THE FUNCTIONS PRESENT IN THIS FILE #
#------------------------------------------------------#
#------------------------------------------------------#
# JavaTest ( stopRun=TRUE, runInit=TRUE )
# isErr ( expression )
# isNumber ( x )
# showProg ( flag, outp, header=FALSE, done=FALSE, tb=1 )
# pasteC ( ... )
# paste_ ( ... )
# pasteR ( x, n )
# pasteNoBlanks ( ..., sep=" ", collapse=NULL, na.rm=FALSE )
# fw0 ( num, digs=NULL, mkseq=TRUE, pspace=FALSE )
# fw0.older ( obj, digs=NULL )
# fw ( x, dec=4, digs=4, w=NULL, ... )
# fw3 ( x, dec=3, digs=3, w=NULL, ... )
# fwp ( x, dec=2, sep=" " )
# roundOutToX ( obj, x=10 )
# clipPaste ( flat=TRUE )
# clipCopy ( txt, sep="" )
# meantrm ( x, p=6 )
# CMT <- getCMT <- getClassModeTypeof ( obj )
# jythonIsGlobal ( )
# python ( jythonStatement )
# pythonGet ( pythonObj )
# pythonSet ( rObj )
# pythonSetDiffName ( pythonObj, rObj )
# pyParse ( strToParse )
# form ( x, dig=3 )
# getNCMT <- getNameClassModeTypeof ( obj )
# countNA01s ( vec )
# insert ( lis, obj, pos=0, objIsMany=FALSE )
# as.path ( ..., ext="", fsep=.Platform$file.sep, expand=TRUE, verbose=TRUE )
# cleanDotDotPath.split ( pathParts, fsep=.Platform$file.sep, expand=TRUE )
# cleanDotDotPath.combine ( splat, fsep=.Platform$file.sep, expand=TRUE )
# makeDictFromCSV ( csvFile )
# isSubstrAtEnd ( x, pattern, ignorecase=TRUE )
# s <- summary2 ( x, rows=6, cols=6, cmt=TRUE )
# c4 ( x, rows=20, cols=4, cmt=TRUE )
# printdims ( X, justTheValue=FALSE )
# topropper ( x )
# topropper_withPunc ( x )
# qy <- quity ( dir='~/' )
# qn <- quitn ( dir='~/' )
# tbs ( n, nl=FALSE )
# pip ( )
# slash ( )
# miniframe ( data, rows=200 )
# makeDictWithIntegerKeys ( KVraw, applyLabels=TRUE )
# chkp <-chkpt ( logStr, chkpOn=TRUE, final=FALSE )
# pgDisconnectAll ( drv=dbDriver("PostgreSQL") )
# mgsub ( pattern, replacement, x, ..., fixed=TRUE )
# cleanChars ( text, replacement="_", Whitelist=NULL )
# replaceBadCharsUnderscore ( str, WhiteList=NULL )
# timeStamp ( seconds=FALSE )
# detectAssignment ( obj, single=TRUE, simplify=FALSE )
# loadbak ( f, env=parent.frame() )
# saveit ( obj, dir=ifelse(exists("outDir"), outDir, as.path(getwd(), "out")), subDir=TRUE, pos=1, addTimeStamp=TRUE, useSeconds=FALSE )
# jesusForData ( ..., dir=dataDir, sub=FALSE, stampFile=TRUE, stampDir=FALSE, pos=1, envir="" )
# savethem <- jesus ( ..., dir=ifelse(exists("outDir"), outDir, as.path(getwd(), "out")), subDir=sub, pos=1, sub=TRUE, stampDir=TRUE, stampFile=FALSE, summary=TRUE, envir="" )
# mkSaveFileNameWithPath ( objName, dir, pos=2, addTimeStamp=FALSE, ext=".Rda" )
# dimToString ( objName, pos=2, prefix="-" )
# plength <- printlength ( opt=200 )
# reminder ( )
# saveToFile_TabDelim ( obj, directory=getwd() )
# retTst ( n )
# allPosCombsList ( dat, choose=seq(ncol(dat)), yName="y" )
# formulasList ( dat, yName="y", VARS.list=NULL, interact=TRUE, intercept=TRUE )
# logscale ( range=2:5, intervals=2, base=10 )
# asCurr ( x, decim=2, noSpacesAfterSymb=1, symbol="$" )
# lP <- listPacker ( receiver, ... )
# lsnf ( ... )
# lsi ( what, invert=FALSE, rm=FALSE )
# devsource ( file, dir="~/Dropbox/dev/R/!ScriptsR/" )
# gitsource ( file, dir="~/git/misc/rscripts/" )
# homesource ( file, dir="~/" )
# source.url ( ... )
# extendToMatch ( source, destin )
# rmDupLines ( obj, trim=T )
# cordl ( ..., length=NULL, justSize=FALSE, crop=TRUE, chop=TRUE )
# paraLineChop ( so, length=NULL, lines=NULL, justSize=FALSE )
# coefTable ( model )
# splitEvery ( string, n, remSpace = FALSE )
# cls ( LINES=100 )
# pkgFind ( toFind )
# regexAll ( pattern, stringVec, replace="@@@", ignore.case=FALSE, fixed=FALSE, perl=FALSE, value=FALSE )
# tbls ( envir=.GlobalEnv )
# colquote ( colNamesAsStrings )
# uniqueRows ( DT )
# getdotsWithEval ( )
# setkeyE ( x, ..., verbose = getOption("datatable.verbose") )
# shift ( x )
# shiftb ( x )
# namesdetect ( x, pattern )
# namesIn ( x, vec, positive=TRUE )
# namesNotIn ( x, vec )
# orderedColumns ( DT, frontCols=NULL, ignoreCase=TRUE, endCols=NULL )
# combineRows ( x )
# wordCount ( obj, words, ignore.case=TRUE, preservePunct=FALSE )
# dateCheck ( d )
# is.allNA ( x )
# invDict ( dict )
# setNamesDict ( DT, dict, replaceMissing=NULL, silent=FALSE )
# uniqueKeys ( DT )
# convertClass ( DT, colnameVector, to, from=NULL, originDate="1970-01-01", excelOriginName=".xlorigin" )
# convertClass.default ( DT, ... )
# convertClass.data.table ( DT, colnameVector, to, from=NULL, originDate="1970-01-01", excelOriginName=".xlorigin" )
# areEqual.slow ( x, na.rm=TRUE )
# areEqual ( x, na.rm=TRUE, tolerance = .Machine$double.eps ^ 0.5, NoWarnings=FALSE )
# CamelCaseSplit ( string, flat=FALSE )
# gapply ( X, FUN, ..., simplify=FALSE, pos=1 )
# xapply ( X, qFUN, ..., simplify=FALSE )
# catTitle ( Title, pref="", suf="", tabs=1, topline=FALSE, dash="-", center=TRUE )
# centerText ( x, eol="\n", padWith=" ", trim=TRUE, tabs="" )
# alignText ( x, eol="\n", padWith=" ", trim=TRUE, tabs="", halign="center" )
# printBox ( x, width=68, dash="~", sides="#", crop=FALSE, topspace=0, bottomspace=0, tabs=1, header="" )
# splitToWidth ( x, width, safetyBreak=100 )
# isFALSE ( x )
# modelDescrFromCall ( ... )
# modelDescrFromCall.Arima ( M )
# modelDescrFromCall.lm ( M )
# modelDescrFromCall.default ( M )
# paste.call ( ordr )
# modelDataSetFromCall ( ... )
# modelDataSetFromCall.Arima ( M )
# modelDataSetFromCall.lm ( M )
# dimCompare ( ..., decr=NA, decreasing=decr, sortOn=NA )
# rangesFromInt ( int, numberOfRanges, sizeOfEach, pairs=TRUE, aslist=TRUE, sequence=TRUE, fractions=FALSE )
# r.t ( x=clipPaste(), header=TRUE, sep=NULL, to=NULL, value=!(is.character(to)), pos=1, file=NULL )
# r.d ( x=clipPaste(), header=TRUE, sep=NULL, to=NULL, value=!(is.character(to)), pos=1, file=NULL )
# First ( silent=FALSE )
# as.path ( ... )
# howManyNAs ( x )
# sortXbyY ( X, Y, justIndex=FALSE, names=FALSE, names.X=names, names.Y=names )
# seasonFromDate ( D, factors=TRUE )
# revString ( x )
# mds ( includeInput=TRUE, x=clipPaste() )
# mkdshr ( x=clipPaste(), space=TRUE, pound="#", dash="-", leftSpace=TRUE, includeInput=TRUE, top=TRUE, minWidth=20, align=NA, mindent=4, dontSmoothPreSpace=FALSE, fancy=FALSE, match=FALSE )
# topAndBottom ( vec, n=1 )
# mr ( x=clipPaste(), mindent=9, minWidth=60, align="left", top=TRUE, match=FALSE, ... )
# mkdsh ( x=clipPaste(), space=TRUE, pound="#", dash="-", leftSpace=TRUE, includeInput=TRUE )
# spacecnt ( x=clipPaste() )
# dtWideToLong ( DT, cols=names(DT), cnames=c("Name", "Value") )
# knito ( input, output=gsub("src", "out", dirname(input)), encoding="UTF-8", ... )
# mbench ( ..., maxSeconds=20, maxReps=200L, verbose=TRUE )
# utilSource ( .Pfm=Sys.info()[['sysname']] )
# plrl ( word.pluarl.form, count, singular=(length(count)==1) )
# whichFactors ( x )
# getNamesFromDTCols ( DT, na.rm=TRUE, uniquify=TRUE )
# orderedHeadTail ( x, n=min(length(x), 5), na.last=TRUE, decreasing=FALSE, logical=FALSE, value=FALSE, f=c("head", "tail") )
# orderedHead ( x, n=min(length(x), 5), na.last=TRUE, decreasing=FALSE, logical=FALSE, value=FALSE )
# orderedTail ( x, n=min(length(x), 5), na.last=TRUE, decreasing=FALSE, logical=FALSE, value=FALSE )
# lib ( pkg, newest=FALSE, dependencies=TRUE, rforge=FALSE, update=FALSE )
# are ( ll, simplify=TRUE )
# findLastSpace ( x, space=" " )
# sourceEntireFolder ( folderName )
# cnt ( col, DT=defaultDT )
# mergeDTlist ( DTlist, suffixes=NULL, checkKeys=TRUE )
#------------------------------------------------------
.Pfm <- Sys.info()[['sysname']]
# Load Memory Functions
try( ## Wrapping in `try` so that if fails, does not affect rest of the utils load
if (.Pfm=="Linux"){
source(path.expand("~/NBS-R/utils/memoryFunctions.R"))
wrkDir <- "~/NBS-R/"
} else
source(path.expand("~/git/misc/rscripts/utils/memoryFunctions.R"))
, silent=TRUE)
.RForge <- "http://R-Forge.R-project.org"
#------------------------------------------------------
JavaTest <- function(stopRun=TRUE, runInit=TRUE) {
## ensures that rJava is up and running. If Java is NOT running and...
## stopRun=T, will throw an error. If stop=False, will throw a warning.
## If runInit=T, will load rJava and run .jinit() prior to running .jcheck()
# Load rJava and initialize java
if (runInit) {
library(rJava)
.jinit()
}
# Run .jCheck
errString <- ".jcheck() failed. Please troubleshoot rJava"
if (isErr(.jcheck())) {
if (stopRun) {
stop(errString)
}
else {
warning(errString)
}
}
}
isErr <- function(expression) {
# Boolean; Tries to evaluate the expresion; returns T if an error is thrown
# Args:
# expression: Make sure to use expression() to pass an expression (dont use Strings)
# Returns:
# T if expression throws an Error // F if expression is evaluated without error
# NOTE: The actual evaluation of the expression is NOT RETURNED
return( inherits(try(eval(expression), silent=T), "try-error") )
}
isNumber <- function(x) {
# the purpose of this function is to avoid the warnings that
# come with 'is.numeric(as.numeric(x))' when x is not a number.
if (is.list(x))
return(lapply(x, isNumber))
if (length(x) > 1)
return(sapply(x, isNumber))
ifelse (nchar(x) == attr(gregexpr("^[[:digit:]]*$", x)[[1]], "match.length"),
is.numeric(as.numeric(x)), FALSE)
}
showProg <- function(flag, outp, header=FALSE, done=FALSE, tb=1) {
# wrapper function for:
# if flag is true, then cat() outp.
# put tabs after any line break
outp <- sub("\n", tbs(tb, T), outp)
# If header or done: set tb to 0, unless user defined value
tb <- ifelse(missing(tb) && (header || done), 0, tb)
if (header)
cat ("","========================","Progress Indication....", sep=tbs(tb,T))
if (flag)
cat(tbs(tb), outp, "\n", sep="")
if (done)
cat ("", "----------------", "Process Complete", "========================", sep=tbs(tb,T))
}
# --------------------------------------------------- #
# #
# PASTE FUNCTIONS #
# #
# --------------------------------------------------- #
## TODO: Put this in the dictionaries file
dict.parens <- c("(" = ")", "[" = "]", "{" = "}", "<" = ">")
# like paste0, but with collapse=""
pasteC <- function(...)
paste(..., collapse="")
paste_ <- function(...)
paste(..., collapse="_")
pasteR <- function(x, n) {
# if n is not a single number, iterate
if (length(n) > 1) {
if (length(n) == length(x))
return(mapply(pasteR, x, n))
return( sapply(n, function(n1) pasteR(x, n1)) )
}
# otehrwise, siple return
pasteC(rep(unlist(x), n))
}
pasteQ <- function(..., q="'", wrap="(", sep="", collapse=", ") {
# Encloses the terms in a quotes.
# If `wrap` is not NULL, also adds those to each end.
# `wrap` defaults to "("..")" and should be set to NULL/FALSE to turn off
# alternates to NULL should be interpreted to NULL
if (is.null(wrap) || is.na(wrap) || wrap=="" || identical(wrap, FALSE))
wrap <- NULL
# `wrapR` is the closing-equiv of `wrap.` If no such equiv found, use `wrap`.
wrapR <- dict.parens[wrap]
wrapR <- ifelse(is.na(wrapR), wrap, wrapR)
paste0(wrap,
paste(q, unlist(list(...)), q
, sep=sep, collapse=collapse)
,wrapR)
}
pasteNoBlanks <-
function(..., sep=" ", collapse=NULL, na.rm=FALSE) {
dots <- list(...)
# remove NAs
if(na.rm)
dots <- dots[!is.na(dots)]
# remove blanks
remove <- identical(sep, paste0(dots, sep)) | (nchar(dots)==0) | (lapply(dots, length)==0)
dots <- dots[!remove]
f <- function(..., sep2=sep, collapse2=collapse){
paste(..., sep=sep2, collapse=collapse2)
}
# return pasted value
return(Reduce(f, dots))
}
# --------------------------------------------------- #
fw0 <- function(num, digs=NULL, mkseq=TRUE, pspace=FALSE) {
## formats digits with leading 0's.
## num should be an integer or range of integers.
## if mkseq=T, then an num of length 1 will be expanded to seq(1, num).
#
# Note that if num is a list, digs will not be automatically compared across the list, and therefore should be manually slected.
# TODO 1: put more error check
# when num is a list, call recursively. mkseq should not expand the list into seq, unless specifically user sets flag or entire list is just length one element
if (is.list(num))
return(lapply(num, fw0, digs=digs, mkseq=ifelse(missing(mkseq), !length(num) > 1, mkseq)))
if (!is.vector(num) & !is.matrix(num)) {
stop("num should be integer or vector")
}
# capture the dims and we will put it back
dims <- dim(num)
# convert strings to numbers
num <- as.numeric(num)
# If num is a single number and mkseq is T, expand to seq(1, num)
if(mkseq && !length(num)>1)
num <- (1:num)
# number of digits is that of largest number or digs, whichever is max
digs <- max(nchar(max(abs(num))), digs)
# if there are a mix of neg & pos numbers, add a space for pos numbers
# (checking first for 0)
# OR if pspace is flagged as TRUE
posSpace <- ifelse((min(num) != 0 & sign(max(num)) != sign(min(num)) | pspace==TRUE), " ", "")
# return: paste appropriate 0's and preface neg/pos mark
ret <-
sapply(num, function(x) ifelse(x<0,
paste0("-", paste0(rep(0, max(0, digs-nchar(abs(x)))), collapse=""), abs(x)),
paste0(posSpace, paste0(rep(0, max(0, digs-nchar(abs(x)))), collapse=""), x)
))
# put back in original form. ie, make it a matrix if it was originally. Otherwise, this will just be NULL
dim(ret) <- dims
return(ret)
}
#-----------------------------------------------
## THIS IS THE OLDER INTERPRETATION OF fw0.
## SPECIFICALLY FOR HOW IT HANDLES fw(199, digs=2)
fw0.older <- function(obj, digs=NULL) {
## formats digits with leading 0's.
## obj should be an integer or range of integers.
if (!is.vector(obj)) {
stop("Obj should be integer or vector")
}
# TODO 1: put more error check
# TODO 2: clean up the if statements. Consider using recursion
# If digs is specified, also consider the obj specified (do not expand to range)
if(!is.null(digs)) {
sequ <- obj
# Otherwise, calculate range, based on length of obj. Then calculate digs
} else {
if(!length(obj)>1) {
sequ <- (1:as.numeric(obj))
} else {
sequ <- obj
}
digs <- nchar(max(sequ))
}
# return
sapply(sequ, function(x) paste0(paste0(rep(0, max(0, digs-nchar(x))), collapse=""), x))
}
#--------------------------------------------
#-----------------------------------------------
## functino to format numerics
fw <- function(x, dec=4, digs=4, w=NULL, ...) {
## wrapper to function format(.)
format(x, nsmall=dec, digits=digs, width=w, ...)
}
## functino to format numerics
fw3 <- function(x, dec=3, digs=3, w=NULL, ...) {
## wrapper to function format(.)
format(x, nsmall=dec, digits=digs, width=w, ...)
}
fwp <- function(x, dec=2, sep=" ", simplify=TRUE, pad=FALSE) {
# Formats as percentage
ret <- sapply(x, function(y) paste(fw3(100*y, dec), "%", sep=sep), simplify=simplify)
# add spaces
if (pad) {
nc <- nchar(ret)
max.char <- max(nc)
ret <- paste0(sapply(max.char- nc, pasteR, x=" "), ret)
}
if (is.null(dim(x)) || !simplify)
return(ret)
dim(ret) <- dim(x)
dimnames(ret) <- dimnames(x)
return(ret)
}
roundOutToX <- function(obj, x=10)
# rounds away from 0 to the nearest x
if(x==0) return(round(obj)) else
ceiling(abs(obj) / x) * (obj/abs(obj)) * x
clipPaste <- function(flat=TRUE) {
# equivalent of CMD+v piped through.
#
# returns whatsever in the OS's clipboard
# if flat is TRUE, then it is collapsed into a single element
# as opposed to multiple lines
con <- pipe("pbpaste", open="rb")
ret <- readLines(con, warn=FALSE)
if (flat)
ret <- paste0(ret, collapse="\n")
close(con)
return(ret)
}
clipCopy <- function(txt, sep="") {
# equivalent of highlighting txt and hitting CMD+C
txt <- paste(txt, collapse="\n")
con <- pipe("pbcopy", "w")
writeLines(txt, con, sep=sep)
close(con)
return(invisible(TRUE))
}
###############################################################
###############################################################
# mean with paramters. Trimming top/bottom p observations (or 1/4 if too few obs present)
meantrm <- function(x, p=6)
mean(x, trim=min(.25, p/length(x)), na.rm=TRUE)
CMT <- getCMT <- getClassModeTypeof <- function(obj) {
# Returns as a vector, the class, mode, typeof of the obj
# getCMT(), CMT() are useful shorthands
return(c("class"=class(obj),"mode"=mode(obj),"typeof"=typeof(obj)))
}
jythonIsGlobal <- function() {
# Checks to see if jython is properly set, if not then sets it
#
# Returns FALSE if jython was not previously set; else returns TRUE
testForjython <- try(class(jython), silent=TRUE)
if (class(testForjython) == "try-error" | testForjython!="jobjRef") {
require(rJython)
.jinit()
jython <<- rJython()
return(FALSE)
}
return(TRUE)
}
python <- function(jythonStatement) {
# Executes in python the string passed
# (Simply a wrapper for an easier way to make python calls)
# Arg:
# jythonStatement: an executable line of python code of type string
#
# Returns:
# passes through the return from the jython.exec command (generally NULL)
jythonIsGlobal()
return(jython.exec(jython, jythonStatement))
# OLD: return(jython.exec(jython, paste(jythonStatement)))
}
pythonGet <- function(pythonObj) {
# From Python Environment, Gets the value of pythonObj.
# (Simply a wrapper for an easier way to get a python object)
#
# Arg:
# pythonObj: name of object in python whose value will be retrieved & returned
#
# Returns:
# the value of pythonObj in the python environment
jythonIsGlobal()
return(jython.get(jython, pythonObj))
# OLD return(jython.get(jython, paste(substitute(pythonObj))))
}
pythonSet <- function(rObj) {
# Sets the value of a python object of same name as rObj to value of rObj.
# same as pythonSetDiffName() but with one less argument to have to type
#
# Arg:
# rObj: object in R; value will be assigned to object of same name in python
#
#
# NOTE: when rObj is a string, pythonSet will create
# a variable whose name is the value of the string
# and whose value is also the value of the string.
#
# Returns:
# passes through the return from the jython.assign command (generally NULL)
jythonIsGlobal()
return(jython.assign(jython, substitute(rObj), rObj))
}
pythonSetDiffName <- function(pythonObj, rObj) {
# Sets the value of a python object named pythonObj to that of rObj
#
# Arg:
# pythonObj: name of object in python environment that will receive rObj
# rObj: object in R whose value is getting assigned to pythonObj
#
# Returns:
# passes through the return from the jython.assign command (generally NULL)
jythonIsGlobal()
return(jython.assign(jython, pythonObj, rObj))
}
pyParse <- function(strToParse) {
# Uses Python to parse a string along any non-char delim
# Arg:
# strToParse: any string needing parsing
#
# Returns:
# list of parsed strings
python("import re")
pythonSetDiffName("strToParse123b4c5", strToParse)
return(pythonGet(paste("re.findall('\\w+', str(strToParse123b4c5))")))
}
form <- function(x, dig=3) {
# just a wrapper for format(x), with options defualted to 3
return(as.numeric(format(x, digits=dig, nsmall=dig)))
}
getNCMT <- getNameClassModeTypeof <- function(obj) {
# Returns as a vector, the name, class, mode, typeof of the obj
# getNCMT is a useful shorthand
return(c("name"=names(obj), "class"=class(obj),"mode"=mode(obj),"typeof"=typeof(obj)))
}
countNA01s <- function(vec) {
# in a given vector, how many are there of each: NA, 0, 1, -1, >1, <(-1), 'other'
# useful for helping to determine if the vector is in fact logical
#
# Args: vec; a vector
# NOTE: if the vector is of class "factor", then 'lt-1' and 'gt1' will not calculate
# in this case, 'nota' (none of the above) is helpful
# CAREFUL: even if 'lt-1', 'gt1' ARE calculated, 'nota' will still count those elements
return( c("NAs"=sum(is.na(vec)),
"lt-1"=sum(vec < (-1) & !is.na(vec)),
"-1s"=sum(vec == (-1) & !is.na(vec)),
"0s"=sum(vec == 0 & !is.na(vec)),
"1s"=sum(vec == 1 & !is.na(vec)),
"gt1"=sum(vec > 1 & !is.na(vec)),
"nota"=sum(vec != 1 & vec != 0 & vec != (-1) & !is.na(vec)) #none of the above
))
}
insert <- function(lis, obj, at=0, objIsMany=FALSE) {
# Inserts obj into list *at* atition at
# all existing items in list, form at onward, are moved forward
# NOTE: If atition > length(list), obj is inserted at end
#
# Args:
# lis: the list object
# obj: the object being inserted
# at: the atition of insert
# objIsMany: (TODO) If T, each item in obj is inserted separately
#
# Returns:
# list with obj inserted at atition
#
# TODO: modify for objIsMany=TRUE
leng <- length(lis)
if (at > leng) { # note strictly greater (not greater or equal!)
return (c(lis,obj))
## TODO: Check for objIsMany
## ifelse(objIsMany, for(i in....))
}
if(at <= 1) {
c(obj,lis)
} else {
c(lis[1:at-1], obj, lis[at:leng])
}
}
#--------------------
sapply.preserving.attributes = function(l, ...) {
# by @Owen from http://stackoverflow.com/questions/7698797/why-does-mapply-not-return-date-objects
r = sapply(l, ...)
attributes(r) = attributes(l)
r
}
#--------------------
as.path <- function(..., ext="", fsep=.Platform$file.sep, expand=TRUE, verbose=TRUE) {
# concatenates the `...` into a valid path, accounting for extra slashes and dot-dot's
##
## Depends on: cleanDotDotPath.split() & cleanDotDotPath.combine()
# grab the dots, remove any null values.
dots <- list(...)
dots <- dots[!sapply(dots, is.null)]
## If first argument starts with "http" or "ftp" and `fsep` hasn't been explicitly set,
## Then fsep should be "/".
if(any(grepl("^(http|ftp)", as.character(dots[[1]]))) && missing(fsep))
fsep <- "/"
# error check
if (any(grepl("^/~", dots[[1]])))
stop ("Path cannot start with `/~`\nDid you mean to use simply `~` ?")
## If starts with fsep, we will preserve it.
startWith <- ifelse(substr(dots[[1]], 1, 1) == fsep, fsep, "")
# Clean up the input (removing superfluous slashes, dots, etc)
cleaned <- lapply(dots, function(x) {
# remove any leading slashes
x <- ifelse(substr(x, 1, 1) == fsep, substr(x, nchar(fsep)+1, nchar(x)), x)
# remove any trailing slashes
lng <- nchar(x)
x <- ifelse(substr(x, lng, lng) == fsep, substr(x, 1, lng-1), x)
# return x to cleaned
x
})
## TODO: this was to prevent some edge case where an element in `cleaned` was blank
## currently, I cannot identify such a case. If found, document it.
cleaned <- cleaned[!sapply(cleaned, function(x) identical(nchar(x), integer(0)))]
# put back any starting fsep
cleaned[[1]] <- paste0(startWith,cleaned[[1]])
# append '.ext' to last item
if (!is.na(ext) && !ext=="")
cleaned[[length(cleaned)]] <- paste0(cleaned[[length(cleaned)]], ".", gsub("^\\.", "", ext))
# checking for '..' ie: "~/git/" + "../out" ==> "~/out"
if(any ( grepl("\\.\\.", cleaned) )) {
return(cleanDotDotPath.split(cleaned, fsep=fsep, expand=expand))
}
# else
putTogether <- do.call(file.path, c(cleaned, fsep=fsep))
if (!expand)
return(putTogether)
return(path.expand(putTogether))
}
cleanDotDotPath.split <- function(pathParts, fsep=.Platform$file.sep, expand=TRUE) {
## PURPOSE: Combine pathParts by taking into account `../`
## eg, if the pathParts is:
# list("~/git/nbs", "../../../Shared/Adobe")
# output should be:
# "/Users/Shared/Adobe"
#
# pathParts: A list of path-like objects that will be concatenated into a single path string
# If it is not a list, it will be coerced into one.
# fsep : a character representing the seaparator between path parts. ie, "/" or "\\"
# expand : If T, "~" will be expanded, normally to "/Users/usrName/" or similar, as per system
# If F, path may be expanded anyway, if the amount of ".."'s require it.
# expand "~usr/"
if (expand)
pathParts <- lapply(pathParts, path.expand)
# pathParts should be a list. Coerce if it isn't
if (!is.list(pathParts))
pathParts <- as.list(pathParts)
# first paste the multi pieces together then split on fsep
putTogether <- do.call(file.path, c(pathParts, fsep=fsep))
splats <- strsplit(putTogether, fsep)
if (length(splats) == 1)
return(cleanDotDotPath.combine(splats[[1]], fsep=fsep, expand=expand))
return(sapply(splats, cleanDotDotPath.combine, fsep=fsep, expand=expand))
}
cleanDotDotPath.combine <- function(splat, fsep=.Platform$file.sep, expand=TRUE) {
# check for superfluous "", which came from 'dir1//dir2.'
# These should be ignored and hence removed
# However if splat[1] is "", this came from '/dir1' and should be preserved
if (any(splat[-1] == ""))
splat <- c(splat[[1]], splat[-1][!splat[-1]==""] )
# now each element in spat is a single directory or a dotdot
# identify which are the dotdots.
isdotdot <- splat == ".."
# check if there are more dotdot's than folders before it. eg:
# FALSE FALSE FALSE FALSE FALSE TRUE FALSE FALSE
# "~" "git" "nbs" ".." ".." ".." "Shared" "Adobe"
if(any(toroot <- cumsum(isdotdot) >= cumsum(!isdotdot))) {
# if we hadn't expanded, rerun this function with expand being TRUE
if(!expand)
return(cleanDotDotPath(pathParts, fsep=fsep, expand=TRUE))
# otherwise..
# the first of the "too many dots" is the new root
root <- min(which(toroot))
# keep only those elements of splat after the new root.
# adding in `""` which signifies "/" when pasted back
splat <- c("", tail(splat, -root))
# re-run this function from the new root
return(cleanDotDotPath(splat, fsep=fsep, expand=expand))
} # else:
# for each index of dotdot, we are going to remove the index of the dir
# that is "right before" it, ie the max of the indecies less than it
areDots <- which(isdotdot) # these are the indecies to the dots
areDirs <- which(!isdotdot) # these are the indecies to the directories
# remove from areDirs, the largest index smaller than dot
for(dot in areDots)
areDirs <- setdiff(areDirs, which.max(areDirs[areDirs < dot]) )
# replace splat with only the indecies being kept. The `as.list` is for the `do.call`
splat <- as.list(splat[areDirs])
# paste it back together with fsep
return(do.call(file.path, c(splat, fsep=fsep)) )
}
#--------------------------
makeDictFromCSV <- function(csvFile) {
# Creates a dictionary out of a CSV file where
# col1 of the CSV are the keys and col2 are the values.
#
# Arg:
# dictCSVPath: A path to a CSV file
#
# Returns a dictionary (list) s|t dict["key"] = "value"
# eg: dict["LooonngWooord"] = "shortwrd"
c <- read.csv(csvFile)
dict <- list(as.character(c[[2]]))
names(dict[[1]]) <-(as.character(c[[1]]))
rm(c) # keep it clean
return(dict[[1]])
}
isSubstrAtEnd <- function(x, pattern, ignorecase=TRUE) {
# Checks if x ends with pattern
if (ignorecase)
return (tolower(substr(x, nchar(x)-(nchar(pattern)-1), nchar(x)))==tolower(pattern))
return (substr(x, nchar(x)-(nchar(pattern)-1), nchar(x))==pattern)
}
s <- smry <- summary2 <- function(x, rows=6, cols=6, cmt=TRUE) {
# prints out a the first rows & cols of x
# if either is negative, prints from the end for that axis
#
# Also print out the Class, Mode, Typeof of the object
cat("\n")
print(CMT(x))
cat("\n")
# check if x is Multidimensional or not
isArr <- ifelse(is.null(dim(x)),FALSE,TRUE)
# MULTIDIMENSIONAL
if (isArr) {
rx <- nrow(x)
cx <- ncol(x)
cat(" TOTAL ROWS: ", rx, "\t TOTAL COLS: ", cx, "\n\n")
#rows to print
if (rows < 0) {
rowsRange <- rx:max(1, rx+rows) #rows is negative
} else {
rowsRange <- 1:min(rows, rx)
}
#cols to print
if (cols < 0) {
colsRange <- cx:max(1, cx+cols) #cols is negative
} else {
colsRange <- 1:min(cols, cx)
}
return(print(x[rowsRange, colsRange]))
}
# UNI-DIMENSIONAL
else {
rx <- length(x)
cat(" TOTAL ROWS: ", rx, "\n\n")
#rows to print
if (rows < 0) {
rowsRange <- rx:max(1, rx+rows) #rows is negative
} else {
rowsRange <- 1:min(rows, rx)
}
return(print(x[rowsRange]))
}
}
c4 <-function(x, rows=20, cols=4, cmt=TRUE) {
## wrapper to function summary2, with rows=20 and cols=4. (hence c4)
## note, calling c4(x, 35) will give 35 rows and 4 cols. (simpler than s(x, 35, 4))
if(is.data.table(x))
if (ncol(x) < 3)
return(x)
else
return(x[
, unique(c( 1:min(ncol(x), (ifelse(missing(rows), 5, rows-2))), ncol(x) + (-1:0) ) )
, with=FALSE
])
# else:
summary2(x, rows, cols, cmt)
}
printdims <- function(X, justTheValue=FALSE) {
nm <- as.character(match.call()[[2]])
if (any(grepl("^\\[\\[", nm)))
nm <- "[ ? ]"
dims <- paste0(nm, ": (", paste(dim(X), collapse=" x "), ")")
if (justTheValue)
return(dims)
else (print(dims))
}
#--------------------------------------------#
topropper <- function(x) {
# Makes Proper Capitalization out of a string or collection of strings.
sapply(x, function(strn)
{ s <- strsplit(strn, "\\s")[[1]]
paste0(toupper(substring(s, 1,1)),
tolower(substring(s, 2)),
collapse=" ")}, USE.NAMES=FALSE)
}
topropper_withPunc <- function(x)
gsub("\\b([a-z])([a-z]+)", "\\U\\1\\E\\2", x, perl=TRUE)
## compare:
# topropper("last-one") # [1] "Last-one"
# topropper_withPunc("last-one") # [1] "Last-One"
#--------------------------------------------#
qy <- quity <- function(dir='~/') {
## quits R and saves the .RData and .Rhistory to dir
setwd(dir)
quit('yes')
}
qn <- quitn <- function(dir='~/') {
## quits R and saves the .RData and .Rhistory to dir
setwd(dir)
quit('no')
}
tbs <- function(n, nl=FALSE) {
# returns a string of n-many tabs, concatenated together
# if nl=T, will preface with a new line char.
return(paste0(ifelse(nl, "\n", ""), paste0(rep("\t", n), collapse="")))
}
pip <- function() {
# for broken keyboard, missing pipe
cat("
|
")
}
slash <- function() {
# for broken keyboard, missing pipe
cat("
\\
")
}
miniframe <- function(data, rows=200) {
## returns a dataframe similar to data but with a randomly selected rows
miniLength <- 200
l <- nrow(data)
ind <- abs(rnorm(miniLength))* l
ind <- round(ind) %% l
cat(ind)
return(data[ind,])
}
makeDictWithIntegerKeys <- function(KVraw, applyLabels=TRUE) {
### problem: if
# we want a dict such that dict[aritstid] = source_name
# PROBLEM: since sourceid's are integers, dict[sourceid] will return the sourceid'th (nth) item
# eg: dict[510] will return the 510th item of dict, not the source whose id is 510 *rather, not necessarily..
# that is, dict[510] != dict["510"]
#
# this wouldnt be a problem if we can ensure that each sourceid gets loaded
# into dict at the position of its integer value
# then dict[sourceid] and dict[sQuote(sourceid)] will return the same value
#
# Args: KVraw should be two-dim matrix with col1==Keys, and col2==Values,
# applyLabels: if T, dict will have names st dict["123"] == dict[123];
# if F, dict["123"] is undefined
# NOTE: The labels are needed in order to be able to make calls like
# which(names(dict) %in% subsetOfKeys) where subsetOfKeys
# is some collection of keys and we want the corresponding values
# Return:
# a one-dim list where dict[key] == value, where key is an integer
## initialize the dict
largestK <- max(KVraw[[1]]) # make sure we create enough room in dict
dict <- rep(NA,largestK) # note that length(dict) >= length(KVraw)
names <- dict
## assign values
for (i in 1:nrow(KVraw) ) {
dict[as.integer(KVraw[[1]][i])] <- KVraw[[2]][i]
names[as.integer(KVraw[[1]][i])] <- as.character(KVraw[[1]][i])
}
## assign labels if option'd