-
Notifications
You must be signed in to change notification settings - Fork 8
/
utilsRS_pub.r
2270 lines (1734 loc) · 71.9 KB
/
utilsRS_pub.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 )
# depth ( x, counter=0 )
# listStr ( obj, showValues=TRUE )
# longestLength ( obj, currentMax=0 )
# listFlatten ( obj, filler=NA )
# tableFlatten ( tableWithLists, filler="" )
# insertListAsCols ( input, target, targetCols, replaceOriginalTargetCol=FALSE, preserveNames=TRUE )
# insertListAsCols.list ( input, target, targetCols, replaceOriginalTargetCol=FALSE, preserveNames=TRUE )
# findGroupRanges ( booleanVec )
# nestedIndx ( this, pre=NULL, thisdepth=0 )
# pasteC ( ... )
# 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=" " )
# clipPaste ( flat=TRUE )
# 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 ( ..., fsep=.Platform$file.sep, expand=TRUE )
# dosDir ( wrkDir, gitData=FALSE, mkdir=FALSE )
# makeDictFromCSV ( csvFile )
# isSubstrAtEnd ( x, pattern, ignorecase=TRUE )
# s <- smry ( x, rows=6, cols=6, cmt=TRUE )
# c4 ( x, rows=20, cols=4, cmt=TRUE )
# topropper ( 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 )
# savethem <- jesus ( ..., dir=ifelse(exists("outDir"), outDir, as.path(getwd(), "out")), subDir=sub, pos=1, sub=TRUE, stampDir=TRUE, stampFile=FALSE, summary=TRUE )
# mkSaveFileNameWithPath ( objName, dir, pos=2, addTimeStamp=FALSE, ext=".Rda" )
# dimToString ( objName, pos=2, prefix="-" )
# plength <- printlength ( opt=200 )
# reminder ( )
# 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 ( ... )
# previouswd ( )
# homewd ( )
# devwd ( )
# gitwd ( )
# msdwd ( )
# devsource ( file, dir="~/Dropbox/dev/R/!ScriptsR/" )
# gitsource ( file, dir="~/git/misc/rscripts/" )
# homesource ( file, dir="~/" )
# txr ( )
# 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 )
# getHumanDateFromEpochDAY ( epochDAY, epoch="1970-01-01 00:00:00", epochtz="UTC", asChar=TRUE )
# splitEvery ( string, n, remSpace = FALSE )
# cls ( )
# pkgFind ( toFind )
# regexAll ( pattern, stringVec, replace="@@@", ignore.case=FALSE, fixed=FALSE, perl=FALSE, value=FALSE )
# savdef <- savedef ( env=parent.frame() )
# loadef ( )
# savenbs ( )
# loadnbs ( )
# fresh ( save=TRUE, utils=TRUE, dt=TRUE, env=parent.frame(), all=NULL )
# 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 )
#------------------------------------------------------
#------------------------------------------------------
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))
}
###############################################################
########### LIST UTILITIES ###########
###############################################################
depth <- function(x, counter=0) {
# Returns the depth of a list-like object.
# Vectors are considered to have depth 0
# an un-nested list has depth 1
ifelse (!is.list(x), counter, max(sapply(x, depth, counter+1)))
}
#--------------------------------------------
listStr <- function(obj, showValues=TRUE) {
# returns a data frame or matrix indicating the structure of a nested list
inds <- nestedIndx(obj)
# flag of -1 indicates to put values first in the df.
if (showValues==-1) {
print("TRUE")
inds <- data.frame(cbind(value=apply(inds, 1, function(ind) obj[[ind[!is.na(ind)]]]), inds))
# flag of 1/T indicates to put values last in the df
} else if (showValues) {
inds <- data.frame(cbind(inds, value=apply(inds, 1, function(ind) obj[[ind[!is.na(ind)]]])))
}
# flag of F indicates no values in the df
return(inds)
}
#--------------------------------------------
longestLength <- function(obj, currentMax=0) {
## returns the length of the longest row or longest list in obj
# obj should be list-like or matrix-like
# If we're at a vector, return the max between its length and running ma
if (is.vector(obj)) # (!is.list(obj) && is.null(dim(obj)))
return(max(currentMax, length(obj)))
# If obj is array or matrix, find the max of each row
if (!is.null(dim(obj)))
return(max(currentMax, apply(obj, 1, longestLength, currentMax=currentMax)))
# If obj is list, find max within each element
if (is.list(obj))
return(max(currentMax, sapply(obj, longestLength, currentMax=currentMax)))
stop("Uknown Object Type")
}
#--------------------------------------------
listFlatten <- function(obj, filler=NA) {
## Flattens obj like rbind, but if elements are of different length, plugs in value filler
## DEPENDS ON: insertListAsCols (and insertListAsCols.list )
# if obj is a list of all single elements, pop them up one level
if (is.list(obj) && all(sapply(obj, length) == 1)) {
obj <- sapply(obj, function(x) x) ## TODO: Double check that this does not need to be transposed. Or perhaps use SimplfyTo..
}
# If obj contains a mix of lists/non-lists elements, then
# all list elements need to be handled first via a recursive call to listFlatten
listIndex <- sapply(obj, is.list)
if (any(listIndex)) {
input <- sapply(obj[listIndex], listFlatten, filler=filler, simplify=FALSE)
# if object is a list without columns (ie, not dataframe, etc), then we can just insert the input back in.
# Otherwise, we need to call isertListAsCols
if (is.list(obj) && is.null(dim(obj))) {
obj[listIndex] <- input
} else {
obj <- insertListAsCols(input, target=obj, targetCols=which(listIndex), replaceOriginalTargetCol=TRUE, preserveNames=TRUE)
}
} # end if (any(listIndex))
# Next, Any elements of obj that are factors need to be converted to character
factorIndex <- sapply(obj, is.factor)
obj[factorIndex] <- sapply(obj[factorIndex], as.character)
# Initialize Vars
bind <- FALSE
# IF ALL ELEMENTS ARE MATRIX-LIKE OR VECTORS, MAKE SURE SAME NUMBER OF COLUMNS
matLike <- sapply(obj, function(x) !is.null(dim(x)))
vecLike <- sapply(obj, is.vector)
# If all matrix-like.
if (all(matLike)) {
maxLng <- max(sapply(obj[matLike], ncol))
obj[matLike] <- lapply(obj[matLike], function(x) t(apply(x, 1, c, rep(filler, maxLng - ncol(x)))))
bind <- TRUE
# If all vector-like
} else if (all(vecLike)) {
maxLng <- max(sapply(obj[vecLike], length))
obj[vecLike] <- lapply(obj[vecLike], function(x) c(x, rep(filler, maxLng - length(x))))
bind <- TRUE
# If all are either matrix- or vector-like
} else if (all(matLike | vecLike)) { # TODO: Double check this. I had this with '&' before. I think that was incorrect.
maxLng <- max(sapply(obj[matLike], ncol), sapply(obj[vecLike], length))
# Add in filler's as needed
obj[matLike] <-
lapply(obj[matLike], function(x) t(apply(x, 1, c, rep(filler, maxLng - ncol(x)))))
obj[vecLike] <-
lapply(obj[vecLike], function(x) c(x, rep(filler, maxLng - length(x))))
bind <- TRUE
}
# If processed and ready to be returned, then just clean it up
if(bind) {
# If obj is a data.frame, then it might be all ready to go
if (is.data.frame(obj) && length(obj) == ncol(obj))
return(obj)
# Otherwise, flatten 'obj' with rbind.
ret <- (do.call(rbind, obj))
colnames(ret) <- paste0("L", fw0(1:ncol(ret), digs=2))
return(ret)
}
# Otherwise, if obj is sitll a list, continue recursively
if (is.list(obj)) {
return(lapply(obj, listFlatten))
}
# If none of the above, return an error.
stop("Unknown object type")
}
#--------------------------------------------
tableFlatten <- function(tableWithLists, filler="") {
# takes as input a table with lists and returns a flat table
# empty spots in lists are filled with value of 'filler'
#
# depends on: listFlatten(.), findGroupRanges(.), fw0(.)
# index which columns are lists
listCols <- sapply(tableWithLists, is.list)
tableWithLists[listCols]
tableWithLists[!listCols]
# flatten lists into table
flattened <- sapply(tableWithLists[listCols], listFlatten, filler=filler, simplify=FALSE)
# fix names
for (i in 1:length(flattened)) colnames(flattened[[i]]) <- fw0(ncol(flattened[[i]]), 2)
# REASSEMBLE, IN ORDER
# find pivot point counts
pivots <- sapply(findGroupRanges(listCols), length)
#index markers
indNonList <- indList <- 1
# nonListGrp <- (0:(length(pivots)/2)) * 2 + 1
# ListGrp <- (1:(length(pivots)/2)) * 2
final <- data.frame(row.names=row.names(tableWithLists))
for (i in 1:length(pivots)) {
if(i %% 2 == 1) {
final <- cbind(final,
tableWithLists[!listCols][indNonList:((indNonList<-indNonList+pivots[[i]])-1)]
)
} else {
final <- cbind(final,
flattened[indList:((indList<-indList+pivots[[i]])-1)]
)
}
}
return(final)
}
#---------------------------------------------
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#___________________________________________%
# Generic form of insertListAsCols
insertListAsCols <- function(input, target, targetCols, replaceOriginalTargetCol=FALSE, preserveNames=TRUE)
UseMethod("insertListAsCols")
#___________________________________________%
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
insertListAsCols.list <- function(input, target, targetCols, replaceOriginalTargetCol=FALSE, preserveNames=TRUE) {
# input should be table-like or a list of table-like elements.
# if input is list or multidimensional, but targetCols has length 1, is an error.
# note: If uncareful, preserveNames=TRUE can cause infinite loop # TODO: insert safetybreak
## ERROR CHECK
if (length(input) != length(targetCols))
stop("length(input) and length(targetCols) do not match")
## If there are no names to preserve, then adjust the flag accordingly
## If there are target names, but not list names, then
if (is.null(names(input))) {
if (is.null(names(target))) {
preserveNames <- FALSE
} else {
names(input) <- paste("L", fw0(seq(length(input)), 2), sep="_")
}
}
# If prserve names, then call function just on names. They get reapplied at end.
if (preserveNames) {
# OLD nms: mapply(function(name, thelist) {t(rep(name, ncol(thelist)))}, names(input), input, SIMPLIFY=FALSE)
nms <- mapply(function(name, thelist) {t(paste(name, 1:ncol(thelist), sep="."))}, names(input), input, SIMPLIFY=FALSE)
targetNames <- insertListAsCols(input=nms, target=rbind(names(target)),
targetCols=targetCols, replaceOriginalTargetCol=replaceOriginalTargetCol, preserveNames=FALSE)
}
# If we are preserving the original, then we add 1 to the index values.
# ie, rOT is 0 if replaceOriginalTargetCol is TRUE
rOT <- as.numeric(!replaceOriginalTargetCol)
## length of targetcols used many times
numbOfSplices <- length(targetCols) # this variable might need a better name. Does 'A B' have one splice (the space) or two (the A and the B)?
## we take the amount of each padding to be the number of columns of each input
padAmounts <- unlist(sapply(input, ncol))
padAmounts[is.null(padAmounts)] <- 1 # TODO: confirm that this in fact is acceptable (and not that we are masking errors)
padAmounts <- padAmounts - (1-rOT)
## Pad target with filler-columns
# a filler column of just NA's will be used for padding
fillerCol <- rep(NA, nrow(target))
for (i in seq_along(targetCols)) {
t <- targetCols[[i]]
ln <- padAmounts[[i]]
#------------------
# This pads 'target' once. Then we have to re-adjust our indicies
#------------------
target.tmp <- target[,1:t, drop=FALSE] # was 's:t+rOT' but I dont think thats needed
for (j in seq(ln))
target.tmp <- cbind(target.tmp, fillerCol)
# if we just padded the last columns of target, then just replace target, else append appropriately
if (t < ncol(target)) {
target <- cbind(target.tmp, target[,(t+1):ncol(target), drop=FALSE])
} else {
target <- target.tmp
}
# increment all targetCols beyond the i'th one by the number of reps, so long as there are any left
if (i < numbOfSplices)
targetCols[(i+1):numbOfSplices] <- targetCols[(i+1):numbOfSplices] + ln
#------------------
} # end for-loop
# Shift target Cols according to whether we are preserving column in current spot or not
targetCols <- targetCols + rOT # shift over 1 if we are preserving the original
# # make a matrix of indexes, we will iterate over each row.
# indxs <- t(mapply(seq, from=targetCols, to=targetCols+padAmounts-rOT)) # Note that padAmounts has already been adjusted by rOT
# OLD
# # Insert the input columns in their appropriate spots in the target
# for (i in seq_along(padAmounts)) {
# target[ indxs[i, ] ] <- input[[i]] # or... <- apply(input[[i]], 2, function(x) x)
# }
# make a matrix of indexes, we will iterate over each row.
indxs <- mapply(seq, from=targetCols, to=targetCols+padAmounts-rOT, SIMPLIFY=FALSE) # Note that padAmounts has already been adjusted by rOT
# Insert the input columns in their appropriate spots in the target
for (i in seq_along(padAmounts)) {
target[ indxs[[i]] ] <- input[[i]] # or... <- apply(input[[i]], 2, function(x) x)
}
# cleanup names of 'target' and remove last NA of 'targetCol'
if (preserveNames) {
names(target) <- targetNames
} else {
names(target) <- 1:ncol(target)
}
# return modified target
return(target)
}
#--------------------------------------------
findGroupRanges <- function(booleanVec) {
# returns list of indexes indicating a series of identical values
pivots <- which(sapply(2:length(booleanVec), function(i) booleanVec[[i]] != booleanVec[[i-1]]))
### THIS ISNT NEEDED...
# if (identical(pivots, numeric(0)))
# pivots <- length(booleanVec)
pivots <- c(0, pivots, length(booleanVec))
lapply(seq(2, length(pivots)), function(i)
seq(pivots[i-1]+1, pivots[i])
)
}
#--------------------------------------------
nestedIndx <- function(this, pre=NULL, thisdepth=0) {
## returns a matrix indicating whose rows are the extended indecies of a nested list
## DEPENDENT ON: listFlatten()
if (!is.list(this))
return(pre)
s <- seq(length(this))
soFar <- lapply (s, function(i) c(pre, i) )
listFlatten (lapply(s, function(i) nestedIndx(this[[i]], pre=soFar[[i]])))
}
#--------------------------------------------
# like paste0, but with collapse=""
pasteC <- function(...)
paste(..., collapse="")
paste_ <- function(...)
paste(..., collapse="_")
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=" ")
# Formats as percentage
lapply(x, function(y) paste(fw3(100*y, dec), "%", sep=sep))
clipPaste <- function(flat=TRUE) {
# returns whatsever in the clipboard
# if flat is true, then it is collapsed into a single element
# as opposed to multiple lines
con <- pipe("pbpaste", open="r")
ret <- readLines(con)
if (flat)
ret <- paste0(ret, collapse="\n")
close(con)
return(ret)
}
###############################################################
###############################################################
# 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, pos=0, objIsMany=FALSE) {
# Inserts obj into lis *at* position
# all existing items in list, form pos onward, are moved forward
# NOTE: If position > len(list), obj is inserted at end
#
# Args:
# lis: the list object
# obj: the object being inserted
# pos: the position of insert
# objIsMany: (TODO) If T, each item in obj is inserted separately
#
# Returns:
# list with obj inserted at position
#
# TODO: modify for objIsMany=TRUE
leng <- len(lis)
if (pos > leng) { # note strictly greater (not greater or equal!)
return (c(lis,obj))
## TODO: Check for objIsMany
## ifelse(objIsMany, for(i in....))
}
if(pos <= 1) {
c(obj,lis)
} else {
c(lis[1:pos-1], obj, lis[pos: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(..., fsep=.Platform$file.sep, expand=TRUE) {
## If starts with fsep, we will preserve it.
startWith <- ifelse(substr(..1,1,1) == fsep, fsep, "")
cleaned <- lapply(list(...), function(x) {
# remove any leading slashes
x <- ifelse(substr(x, 1, 1) == fsep, substr(x, 2, 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
})
# put back any starting fsep
cleaned[[1]] <- paste0(startWith,cleaned[[1]])
if (!expand)
return(do.call(file.path, c(cleaned, fsep=fsep)))
return(path.expand(do.call(file.path, c(cleaned, fsep=fsep))))
}
#--------------------------
dosDir <- function(wrkDir, gitData=FALSE, mkdir=FALSE) {
# makes data, out, src directory inside the directory wrkDir
# and creates variables with full path to these directories
# in the parent environment (the environment that called this func)
#
grp <- list("data", "out", "src")
# create vars (+'Dir') and vals (paths)
vars <- paste0(grp, "Dir")
vals <- mapply(as.path, wrkDir, grp, MoreArgs=list(expand=FALSE), USE.NAMES=FALSE)
# if flagged, data dir will be in different directory
if (gitData)
# vals[[which(grp=="data")]] <- sub("/git/", "/gitData/", eval(vals[[1]], envir=parent.frame()))
vals[[which(grp=="data")]] <- sub("/git/", "/gitData/", vals[[which(grp=="data")]])
# if flagged, create directories if they do not exist
if (mkdir)
sapply(path.expand(vals), dir.create, showWarnings=FALSE, recursive=TRUE)
# assign vals to appropriate var names in the calling environment
mapply(assign, vars, vals, MoreArgs=c(pos=parent.frame()))
}
#--------------------------
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 <-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 smry, 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))
smry(x, rows, cols, cmt)
}
topropper <- function(x) {
# Makes Proper Capitalization out of a string or collection of strings.
sapply(x, function(strn)
{ s <- strsplit(strn, " ")[[1]]
paste0(toupper(substring(s, 1,1)),
tolower(substring(s, 2)),
collapse=" ")}, USE.NAMES=FALSE)
}
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="")))