-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathutils.R
3011 lines (2724 loc) · 91.7 KB
/
utils.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
### utilities
# psum, rescaler, bind_all, cbindx, rbindx, rbindfill, rbindfill2, rbindlist,
# rbindlist2, interleave, outer2, merge2, locf, roll_fun, regcaptures,
# regcaptures2, cast, melt, View2, view, rapply2, sort_matrix, insert,
# insert_matrix, tryCatch2, rleid, rleid2, droplevels2, combine_levels,
# combine_regex, rownames_to_column, column_to_rownames, split_nth, sort2,
# response, response2, xtable, factor2, switch2, ave_dt, which.min2, which.max2
#
# rawr_ops:
# %ni%, %==%, %||%, %sinside%, %winside%, %inside%, %:%
#
# rawr_ls:
# lss, lsf, lsp
#
# unexported:
# islist, where_, where, dots, name_or_index, rm_na_dimnames, insert_
###
islist <- function(x) {
## is.list(data.frame()); rawr:::islist(data.frame())
inherits(x, 'list')
}
where_ <- function(x, env = environment(NULL)) {
if (identical(env, emptyenv()))
stop(x, ' not found', call. = FALSE)
if (exists(x, env, inherits = FALSE))
env else Recall(x, parent.env(env))
}
where <- function(x) {
## recursively find env where x is defined
stopifnot(
is.character(x),
length(x) == 1L
)
sys <- sys.frames()
for (env in sys)
if (exists(x, env, inherits = FALSE))
return(env)
where_(x)
}
dots <- function(...) {
## rawr:::dots(mean, 1, x = y, rnorm(5))
# eval(sys.call())
eval(substitute(alist(...)))
}
name_or_index <- function(x, y = NULL) {
## return integer vector where x occurs in y
## rawr:::name_or_index(c('1', '3', 'e'))
## rawr:::name_or_index(c('a', 'c', 'e'), letters)
## table is given priority over integer, eg, idx = 27 instead of 4
## rawr:::name_or_index(c('a', '4', 'e'), c(letters, '4'))
suppressWarnings(
ix <- as.integer(x)
)
if (!is.null(y)) {
iy <- match(x, y)
replace(iy, is.na(iy), ix[is.na(iy)])
} else ix
}
#' rawr operators
#'
#' Some useful binary operators.
#'
#' \code{\%ni\%} is the negation of \code{\link[base]{\%in\%}}.
#'
#' \code{\%winside\%} and \code{\%sinside\%} return a logical vector
#' indicating if \code{x} is weakly or strongly inside \code{interval}.
#' \code{\%inside\%} is an alias for \code{\%winside\%} to preserve existing
#' code.
#'
#' \code{\%==\%} is an operator combining the qualities of \code{\link{==}}
#' and \code{\link{\%in\%}} to compare vectors in a pairwise manner which may
#' include \code{\link{NA}}s.
#'
#' \code{\%||\%} is useful for a function, \code{f}, that may return a value
#' or \code{NULL}; however if \code{NULL} is the return value of \code{f}, it
#' is desirable to return some other default value.
#'
#' \code{\%:\%} is useful for obtaining a range of a vector (usually
#' \code{colnames} or \code{names} of a matrix or data frame) by literal
#' character strings rather than by index.
#'
#' @param x vector or \code{NULL}; the values to be matched
#' @param table vector or \code{NULL}; the values to be matched against
#' @param interval numeric vector of length two representing the interval
#' @param a,b raw, logical, "number-like" vectors or objects
#' @param object a \emph{named} vector or list, a matrix or data frame
#' @param range a numeric or character vector of length two with the indices
#' or names from \code{object}, generally of the structure \code{c(from, to)}
#'
#' @seealso
#' \code{\link{==}}, \code{\link{\%in\%}}, \code{\link{||}}
#'
#' @examples
#' ## notin
#' 1:5 %ni% 3:5
#'
#'
#' ## weakly/strongly inside
#' c(0, 4) %winside% c(0, 4)
#' c(0, 4) %sinside% c(0, 4)
#'
#' -5:5 %winside% c(0, 5)
#' -5:5 %sinside% c(0, 5)
#'
#'
#' ## %in% plus ==
#' a <- c(1, NA, 2)
#' b <- c(2, NA, 1)
#' ## not desired
#' a == b # FALSE NA FALSE
#' a %in% b # TRUE TRUE TRUE
#' ## desired results
#' a %==% b # FALSE TRUE FALSE
#'
#'
#' # NULL | TRUE # logical(0)
#' NULL %|% TRUE # TRUE
#' # logical() | TRUE # logical(0)
#' logical() %|% TRUE # TRUE
#'
#'
#' 1:5 %:% c(3, 5)
#' letters %:% c('e', 'n')
#'
#' ## these are equivalent
#' mtcars %:% c('hp', 'vs')
#' mtcars %:% c(4, 8)
#' names(mtcars[, 4:8])
#'
#' @aliases oror notin inside
#' @name rawr_ops
NULL
#' @rdname rawr_ops
#' @export
'%ni%' <- function(x, table) {
!(match(x, table, nomatch = 0L) > 0L)
}
#' @rdname rawr_ops
#' @export
`%sinside%` <- function(x, interval) {
interval <- sort(interval)
x > interval[1L] & x < interval[2L]
}
#' @rdname rawr_ops
#' @export
`%winside%` <- function(x, interval) {
interval <- sort(interval)
x >= interval[1L] & x <= interval[2L]
}
#' @rdname rawr_ops
#' @export
`%inside%` <- `%winside%`
#' @rdname rawr_ops
#' @export
`%==%` <- function(a, b) {
(is.na(a) & is.na(b)) | (!is.na(a) & !is.na(b) & a == b)
}
#' @rdname rawr_ops
#' @export
`%|%` <- function(a, b) {
if (length(a))
a else b
}
if (getRversion() < '4.4.0') {
`%||%` <- function(a, b) {
if (!is.null(a))
a else b
}
}
#' @rdname rawr_ops
#' @export
`%:%` <- function(object, range) {
FUN <- if (!is.null(dim(object))) {
if (is.matrix(object)) colnames else names
} else identity
wh <- if (is.numeric(range))
range else which(FUN(object) %in% range)
FUN(object)[seq(wh[1L], wh[2L])]
}
#' List utilities
#'
#' These functions begin with \code{ls} and list different things. \code{lss}
#' is an "improved" \code{\link{ls}} which gives more details of objects in
#' the workspace such as type, size, and dimensions; \code{lsp} lists
#' \code{p}ackage contents, i.e., exported and/or non exported objects,
#' methods, lazy data, etc.; and \code{lsf} lists package \code{f}iles. See
#' details and examples.
#'
#' \code{lsf} prints package files (e.g., \code{DESCRIPTION}, \code{NEWS},
#' \code{INDEX}, \code{NAMESPACE}, etc.) to console and returns (invisibly)
#' the files parsed for easier use.
#'
#' \code{lsp} is a helper function to list exported (\code{?"::"}) and non
#' exported (\code{?":::"}) functions (and other features from a package's
#' \code{NAMESPACE} file).
#'
#' Note that \code{base} and older packages do not have a \code{NAMESPACE}
#' file in which case, for \code{base} packages, \code{lsp} returns
#' \code{ls(.BaseNamespaceEnv, all.names = TRUE)}, and throws an error
#' otherwise.
#'
#' Possible values for \code{what} are "\code{all}" (default), \code{NULL},
#' "\code{exports}", "\code{imports}", "\code{dynlibs}", "\code{lazydata}",
#' "\code{path}", "\code{S3methods}", "\code{spec}", and others depending on
#' the package.
#'
#' \code{lsp(packagename, "?")} to see options for a specific package.
#'
#' \code{lsp(packagename, NULL)} to return all information in a list.
#'
#' @param pos argument specifying the environment as a position in search list
#' or a "list-like" object such as a data frame or list of objects
#' @param pattern optional \code{\link{regex}}; for \code{lss} only names
#' matching \code{pattern} are returned; \code{\link{glob2rx}} can be used
#' to convert wildcard patterns to regular expressions; for \code{lsp} a text
#' pattern or regular expression passed to \code{\link{grep}} to filter the
#' results
#' @param by variable to order output ("type", "size" (default), "sizef",
#' "nrow", or "ncol")
#' @param all.names logical; if \code{TRUE}, all object names are returned; if
#' \code{FALSE}, names which begin with a \code{.} are omitted
#' @param decreasing logical; if \code{TRUE}, displays output in decreasing
#' order
#' @param n number of objects to displace if \code{head} is \code{TRUE}
#' @param package package name, as a \code{\link{name}} or literal character
#' string
#' @param file file to return as a character string; usual options are
#' \code{"DESCRIPTION"}, \code{"NEWS"}, \code{"INDEX"}, \code{"NAMESPACE"};
#' partial matching is supported and case is ignored
#' @param what what to get; \code{"all"} is default which returns all exported
#' and non exported functions in \code{package}; see details for more
#'
#' @return
#' \code{lss} returns a data frame with each object from the workspace with
#' type, object size, and dimensions for each. \code{lsf} (invisibly) returns
#' the contents of \code{file} after being printed to the console. \code{lsp}
#' returns a vector of character strings.
#'
#' @seealso
#' \code{\link{ls}}; \code{\link{search}}; \code{\link[rawr2]{rawr_parse}}
#'
#' @examples
#' ## lss(): use like ls()
#' lss()
#' a <- rnorm(100000)
#' b <- matrix(1, 1000, 100)
#' lss()
#'
#' ## lsf(): these are equivalent ways to use
#' lsf(rawr)
#' lsf(rawr, 'DESCRIPTION')
#' lsf('rawr', 'des')
#'
#' ## lsp: see the contents of a package
#' lsp(rawr)
#'
#' ## return all one- or two-character functions from base package
#' lsp(base, pat = '^.{1,2}$')
#'
#' ## for "what" options
#' lsp('rawr', '?')
#'
#' ## library path
#' lsp('rawr', 'path')
#' system.file(package = 'rawr')
#'
#' ## to return everything
#' lsp('rawr')
#'
#' ## data sets
#' lsp('rawr', 'lazydata')
#'
#' @name rawr_ls
NULL
#' @rdname rawr_ls
#' @export
lss <- function(pos = 1L, pattern, by = NULL, all.names = FALSE,
decreasing = TRUE, n = Inf) {
if (!length(ls(envir = as.environment(pos))))
return(character(0L))
lso <- ls(pos = pos, pattern = pattern, all.names = all.names)
res <- lapply(lso, function(name) {
obj <- get(name, pos = pos)
type <- mode(obj)
type <- ifelse(is.na(type), type, as.character(class(obj))[1L])
size <- object.size(obj)
data.frame(
object = name, type = type, size = as.numeric(size),
sizef = format(size, units = 'auto'),
nrow = ifelse('function' %in% type, NA, NROW(obj)),
ncol = ncol(obj) %||% NA, stringsAsFactors = FALSE
)
})
res <- do.call('rbind', res)
res$` ` <- symnum(
unlist(res$size), corr = FALSE, na = FALSE,
cutpoints = c(-Inf, 0.001, 0.1, 0.5, 1, Inf) * 1024 ^ 3,
symbols = c(' ', '.', '*', '**', '***')
)
if ((mb <- sum(res$size) / (1024 ^ 2)) > 100)
on.exit(message(sprintf('Total size: %.0f Mb', mb)))
if (!is.null(by))
res <- res[order(res[, by], decreasing = decreasing), ]
head(res, n)
}
#' @rdname rawr_ls
#' @export
lsf <- function(package, file = 'DESCRIPTION') {
## DESCRIPTION, INDEX, NEWS, NAMESPACE
package <- as.character(substitute(package))
fp <- do.call('lsp', list(package = package, what = 'path'))
lf <- list.files(fp)
ff <- lf[grepl(sprintf('(?i)^%s.*$', file), lf, perl = TRUE)]
if (!length(ff)) {
message(sprintf('File \'%s\' not found', file))
return(invisible(NULL))
}
f <- readLines(con <- file(fp <- file.path(fp, ff)))
on.exit(close(con))
message(sprintf('Showing file:\n%s\n', fp))
cat(f, sep = '\n')
invisible(f)
}
#' @rdname rawr_ls
#' @export
lsp <- function(package, what, pattern) {
if (!is.character(substitute(package)))
package <- deparse(substitute(package))
ns <- asNamespace(package)
if (missing(pattern))
pattern <- '.*'
## base package does not have NAMESPACE
if (isBaseNamespace(ns)) {
res <- ls(.BaseNamespaceEnv, all.names = TRUE)
res[grep(pattern, res, perl = TRUE, ignore.case = TRUE)]
} else {
## for non base packages
if (exists('.__NAMESPACE__.', envir = ns, inherits = FALSE)) {
wh <- get('.__NAMESPACE__.', inherits = FALSE,
envir = asNamespace(package, base.OK = FALSE))
what <- if (missing(what)) 'all'
else if ('?' %in% what)
return(ls(wh))
else ls(wh)[pmatch(what[1L], ls(wh))]
if (!is.null(what) && !any(what %in% c('all', ls(wh))))
stop('\'what\' should be one of ',
paste0(shQuote(ls(wh)), collapse = ', '),
', or \'all\'', domain = NA)
res <- sapply(ls(wh), getNamespaceInfo, ns = ns)
res <- rapply(res, ls, classes = 'environment',
how = 'replace', all.names = TRUE)
if (is.null(what))
return(res[grep(pattern, res, perl = TRUE, ignore.case = TRUE)])
if (what %in% 'all') {
res <- ls(getNamespace(package), all.names = TRUE)
return(res[grep(pattern, res, perl = TRUE, ignore.case = TRUE)])
}
if (!any(what %in% ls(wh)))
message(sprintf('No NAMESPACE file found for package %s.', package))
else {
res <- res[[what]]
res[grep(pattern, res, perl = TRUE, ignore.case = TRUE)]
}
}
}
}
#' Pairwise binary functions
#'
#' Perform binary operations on vectors, matrices, or data frames.
#'
#' @param ... numeric vectors, matrices, or data frames with equal dimensions
#' @param na.rm logical; if \code{TRUE}, omits missing values (including
#' \code{\link{NaN}}) from calculations
#' @param FUN a binary function
#'
#' @return
#' An object similar to input objects after successively combining elements
#' with \code{FUN}.
#'
#' @seealso
#' \code{\link{pmin}}; \code{\link{pmax}}
#'
#' @examples
#' x <- c(-1, NA, 4, 15)
#' y <- c(NA, NA, 6, -1)
#'
#' x + y
#' psum(x, y)
#' psum(x, y, na.rm = TRUE)
#'
#' x <- matrix(x, 4, 4)
#' y <- matrix(y, 4, 4)
#' x + y
#' psum(x, y)
#' psum(x, y, na.rm = TRUE)
#'
#' x - y - x
#' pfun(x, y, x, FUN = `-`)
#' pfun(x, y, x, FUN = `-`, na.rm = TRUE)
#'
#' @export
pfun <- function(..., na.rm = FALSE, FUN = `+`) {
l <- list(...)
na <- lapply(l, is.na)
na <- Reduce(`+`, na) == length(l)
if (na.rm)
l <- lapply(l, function(x) {x[is.na(x)] <- 0; x})
res <- Reduce(FUN, l)
res[na] <- NA
res
}
#' @rdname pfun
#' @export
psum <- function(..., na.rm = FALSE) {
pfun(..., na.rm = na.rm, FUN = `+`)
}
#' Rescale numeric vector
#'
#' Rescale a numeric vector to have specified maximum and minimum; modified
#' from the \pkg{scales} package.
#'
#' @param x numeric vector of values
#' @param to output range (numeric vector of length two)
#' @param from input range (numeric vector of length two); if not given,
#' \code{from} is calculated from the range of \code{x}
#'
#' @seealso
#' \code{\link[scales]{rescale}}; \code{\link[scales]{zero_range}}
#'
#' @examples
#' rescaler(1:5, to = c(0, 1))
#' rescaler(1:5, to = c(0, 100))
#' rescaler(5, to = c(0, 100), from = c(0, 25))
#'
#' @export
rescaler <- function (x, to = c(0, 1), from = range(x, na.rm = TRUE)) {
zero_range <- function(x, tol = .Machine$double.eps * 100) {
if (length(x) == 1L)
return(TRUE)
if (length(x) != 2L)
stop('\'x\' must be length one or two')
if (any(is.na(x)))
return(NA)
if (x[1L] == x[2L])
return(TRUE)
if (all(is.infinite(x)))
return(FALSE)
m <- min(abs(x))
if (m == 0)
return(FALSE)
abs((x[1L] - x[2L]) / m) < tol
}
if (zero_range(from) || zero_range(to))
rep_len(mean(to), length(x))
else (x - from[1L]) / diff(from) * diff(to) + to[1L]
}
#' Bind objects
#'
#' Utilities for binding objects with inconsistent dimensions.
#'
#' \code{bind_all} and \code{rbindfill} are used for binding vectors,
#' the latter specifically for \code{\link{rbind}}ing \emph{named} vectors
#' \emph{a la} a "stacking" merge.
#'
#' \code{cbindx} and \code{rbindx} take vector-, matrix-, and data frame-like
#' objects and bind normally, filling with \code{NA}s where dimensions are
#' not equal.
#'
#' \code{rbindfill} stacks \emph{named} vectors by initializing a matrix
#' with all names and filling with \code{...} by row in the order given.
#' The column names will be a vector of the unique names in the order they
#' were given.
#'
#' \code{rbindfill2} row-binds data frames with zero or more common column
#' names. \code{rbindfill2} starts with the first data frame given and
#' \code{rbind}s subsequent data frames adding new columns of \code{NA} as
#' needed to bind. Any columns with matching names will be aggregated;
#' otherwise, data frames without a matching column of data will be filled
#' with \code{NA}.
#'
#' \code{rbindlist} converts a list of vectors into a long data frame with
#' two columns: the list index where each value was stored and the values
#' themselves. A third column will be added if \code{use.names = TRUE} which
#' will keep the names of each vector.
#'
#' \code{rbindlist2} uses \code{rbindlist} to expand data frames with one or
#' more nested columns.
#'
#' @param ... for \code{bind_all} and \code{rbindfill}, vectors;
#' \code{cbindx} and \code{rbindx} will accept vectors, matrices, data
#' frames; data frames should be used with \code{rbindfill2} but matrices
#' (or a combination) will work, but a data frame is returned;
#' \code{rbindlist} accepts vectors or one or more lists
#' @param which joining method; \code{'rbind'} or \code{'cbind'}
#' @param deparse.level integer controlling the construction of labels in
#' the case of non-matrix-like arguments (for the default method):\cr
#' \code{deparse.level = 0} constructs no labels; the default; \cr
#' \code{deparse.level = 1} or \code{2} constructs labels from the argument
#' names \cr see \code{\link{cbind}}
#' @param use.rownames logical; for \code{rbindfill2}, if \code{TRUE}, data
#' frames in a \emph{named} list will retain corresponding rownames; the
#' default is to remove rownames (note that this parameter is ignored if
#' \code{...} is not a named list)
#'
#' for \code{rbindlist} and \code{rbindlist2}, return a data frame with or
#' without rownames; for \code{rbindlist2}, if \code{data} has no row names
#' set (i.e., are \code{"1", "2", ...}), then the default is \code{FALSE}
#' @param use.names logical; if \code{TRUE} and vectors are named, names
#' are preserved and added as a column
#' @param data a matrix or data frame
#' @param column for \code{rbindlist2}, the column(s) to be unnested
#' @param split,fixed,perl arguments passed to \code{\link{strsplit}}
#' controlling how nested column text should be split
#'
#' @seealso
#' \code{\link{cbind}}; \code{\link{rbind}}; \code{\link{interleave}};
#' \code{\link[rawr2]{clist}}; \pkg{qpcR}
#'
#' @examples
#' bind_all(1:5, 1:3, which = 'cbind')
#' bind_all(1:5, 1:3, which = 'rbind')
#'
#' m1 <- matrix(1:4)
#' m2 <- matrix(1:4, 1)
#'
#' cbindx(m1, m2)
#' rbindx(m1, m2)
#' rbindx(mtcars, m2)
#'
#'
#' ## "stack" named vectors
#' f <- function(x) setNames(letters[x], LETTERS[x])
#' x <- lapply(list(1:5, 3:6, 2:7, 26), f)
#' do.call('rbindfill', x)
#'
#' ## "stack" matrices or data frames
#' colnames(m1) <- 'B'
#' colnames(m2) <- LETTERS[1:4]
#' rbindfill2(m1, m2)
#' rbindfill2(m2, m1)
#'
#' set.seed(1)
#' dd <- matrix(NA, nrow = 1, ncol = 10)
#' dd <- as.data.frame(col(dd))
#' l <- setNames(lapply(1:5, function(x) dd[, sample(x), drop = FALSE]),
#' letters[1:5])
#'
#' Reduce('rbindfill2', l) ## or do.call('rbindfill2', l)
#' do.call('rbindfill2', c(l, use.rownames = TRUE))
#' rbindfill2(l$c, l$e)
#'
#' rbindfill2(head(mtcars), head(cars))
#'
#'
#' ## "stack" a list of vectors with differing lengths
#' rbindlist(1:5)
#' rbindlist(1:5, 1:5)
#'
#' l <- lapply(1:4, sequence)
#' rbindlist(l)
#' rbindlist(l[4L])
#'
#' names(l) <- LETTERS[1:4]
#' rbindlist(l)
#' rbindlist(l[4L])
#'
#' l <- lapply(l, function(x) setNames(x, letters[x]))
#' rbindlist(l, use.names = TRUE)
#' rbindlist(unname(l), use.names = TRUE)
#'
#'
#' ## unnest and stack a data frame or matrix
#' dd <- data.frame(
#' id = 1:4, x = rnorm(4), y = sapply(l, toString),
#' z = sapply(l, paste, collapse = '...')
#' )
#' rbindlist2(dd, 'y')
#'
#' ## rownames are kept if data contains non default rownames
#' rbindlist2(`rownames<-`(dd, letters[1:4]), 'y')
#'
#' ## multiple columns can be expanded sequentially
#' rbindlist2(dd, c('y', 'z'))
#' rbindlist2(dd, 'y', split = '\\W+(?![^3]+3)', perl = TRUE)
#'
#' @name bindx
NULL
#' @rdname bindx
#' @export
bind_all <- function(..., which) {
if (missing(which))
stop('specify combining method: \'rbind\' or \'cbind\'')
l <- list(...)
if (any(sapply(l, function(x) !is.null(dim(x)))))
warning('bind_all is intended for vectors: use cbindx or rbindx instead.')
l <- lapply(l, `length<-`, max(sapply(l, length)))
do.call(which, l)
}
#' @rdname bindx
#' @export
cbindx <- function (..., deparse.level = 1L) {
na <- nargs() - (!missing(deparse.level))
deparse.level <- as.integer(deparse.level)
stopifnot(
0L <= deparse.level,
deparse.level <= 2L
)
argl <- list(...)
while (na > 0L && is.null(argl[[na]])) {
argl <- argl[-na]
na <- na - 1L
}
if (na == 0L)
return(NULL)
if (na == 1L) {
if (isS4(..1))
return(cbind2(..1))
else return(matrix(...)) ##.Internal(cbind(deparse.level, ...)))
}
if (deparse.level) {
symarg <- as.list(sys.call()[-1L])[1L:na]
Nms <- function(i) {
if (is.null(r <- names(symarg[i])) || r == '') {
if (is.symbol(r <- symarg[[i]]) || deparse.level == 2L)
deparse(r)
} else r
}
}
## deactivated, otherwise no fill in with two arguments
if (na == 0) {
r <- argl[[2L]]
fix.na <- FALSE
} else {
nrs <- unname(lapply(argl, nrow))
iV <- sapply(nrs, is.null)
fix.na <- identical(nrs[(na - 1):na], list(NULL, NULL))
## deactivated, otherwise data will be recycled
#if (fix.na) {
# nr <- max(if (all(iV)) sapply(argl, length) else unlist(nrs[!iV]))
# argl[[na]] <- cbind(rep(argl[[na]], length.out = nr),
# deparse.level = 0)
#}
if (deparse.level) {
if (fix.na)
fix.na <- !is.null(Nna <- Nms(na))
if (!is.null(nmi <- names(argl)))
iV <- iV & (nmi == '')
ii <- if (fix.na)
2:(na - 1L) else 2:na
if (any(iV[ii])) {
for (i in ii[iV[ii]])
if (!is.null(nmi <- Nms(i)))
names(argl)[i] <- nmi
}
}
## filling with NA's to maximum occuring nrows
nRow <- as.integer(sapply(argl, function(x) NROW(x)))
maxRow <- max(nRow, na.rm = TRUE)
argl <- lapply(argl, function(x)
if (is.null(nrow(x))) {
c(x, rep(NA, maxRow - length(x)))
} else rbindx(x, matrix(nrow = maxRow - nrow(x), ncol = ncol(x))))
r <- do.call('cbind', c(argl[-1L], list(deparse.level = deparse.level)))
}
d2 <- dim(r)
r <- cbind2(argl[[1L]], r)
r <- rm_na_dimnames(r)
if (deparse.level == 0L)
return(r)
ism1 <- !is.null(d1 <- dim(..1)) && length(d1) == 2L
ism2 <- !is.null(d2) && length(d2) == 2L && !fix.na
if (ism1 && ism2)
return(r)
Ncol <- function(x) {
d <- dim(x)
if (length(d) == 2L)
d[2L]
else as.integer(length(x) > 0L)
}
nn1 <- !is.null(N1 <- if ((l1 <- Ncol(..1)) && !ism1) Nms(1L))
nn2 <- !is.null(N2 <- if (na == 2L && Ncol(..2) && !ism2) Nms(2L))
if (nn1 || nn2 || fix.na) {
if (is.null(colnames(r)))
colnames(r) <- rep.int('', ncol(r))
setN <- function(i, nams) colnames(r)[i] <<- if (is.null(nams)) ''
else nams
if (nn1)
setN(1L, N1)
if (nn2)
setN(1L + l1, N2)
if (fix.na)
setN(ncol(r), Nna)
}
r
}
#' @rdname bindx
#' @export
rbindx <- function (..., deparse.level = 1L) {
na <- nargs() - (!missing(deparse.level))
deparse.level <- as.integer(deparse.level)
stopifnot(
0L <= deparse.level,
deparse.level <= 2L
)
argl <- list(...)
while (na > 0L && is.null(argl[[na]])) {
argl <- argl[-na]
na <- na - 1L
}
if (na == 0L)
return(NULL)
if (na == 1L) {
if (isS4(..1))
return(rbind2(..1))
else return(matrix(..., nrow = 1L)) ##.Internal(rbind(deparse.level, ...)))
}
if (deparse.level) {
symarg <- as.list(sys.call()[-1L])[1L:na]
Nms <- function(i) {
if (is.null(r <- names(symarg[i])) || r == '') {
if (is.symbol(r <- symarg[[i]]) || deparse.level == 2)
deparse(r)
} else r
}
}
## deactivated, otherwise no fill in with two arguments
if (na == 0L) {
r <- argl[[2L]]
fix.na <- FALSE
} else {
nrs <- unname(lapply(argl, ncol))
iV <- sapply(nrs, is.null)
fix.na <- identical(nrs[(na - 1L):na], list(NULL, NULL))
## deactivated, otherwise data will be recycled
#if (fix.na) {
# nr <- max(if (all(iV)) sapply(argl, length) else unlist(nrs[!iV]))
# argl[[na]] <- rbind(rep(argl[[na]], length.out = nr),
# deparse.level = 0)
#}
if (deparse.level) {
if (fix.na)
fix.na <- !is.null(Nna <- Nms(na))
if (!is.null(nmi <- names(argl)))
iV <- iV & (nmi == '')
ii <- if (fix.na)
2:(na - 1L) else 2:na
if (any(iV[ii])) {
for (i in ii[iV[ii]])
if (!is.null(nmi <- Nms(i)))
names(argl)[i] <- nmi
}
}
## filling with NAs to maximum occuring ncols
nCol <- as.integer(sapply(argl, function(x)
if (is.null(ncol(x)))
length(x) else ncol(x)))
maxCol <- max(nCol, na.rm = TRUE)
argl <- lapply(argl, function(x)
if (is.null(ncol(x))) {
c(x, rep(NA, maxCol - length(x)))
} else cbind(x, matrix(nrow = nrow(x), ncol = maxCol - ncol(x))))
## create a common name vector from the
## column names of all 'argl' items
namesVEC <- rep(NA, maxCol)
for (i in seq_along(argl)) {
CN <- colnames(argl[[i]])
m <- !(CN %in% namesVEC)
namesVEC[m] <- CN[m]
}
## make all column names from common 'namesVEC'
for (j in seq_along(argl)) {
if (!is.null(ncol(argl[[j]]))) colnames(argl[[j]]) <- namesVEC
}
r <- do.call('rbind', c(argl[-1L], list(deparse.level = deparse.level)))
}
d2 <- dim(r)
## make all column names from common 'namesVEC'
colnames(r) <- colnames(argl[[1L]])
r <- rbind2(argl[[1L]], r)
r <- rm_na_dimnames(r)
if (deparse.level == 0L)
return(r)
ism1 <- !is.null(d1 <- dim(..1)) && length(d1) == 2L
ism2 <- !is.null(d2) && length(d2) == 2L && !fix.na
if (ism1 && ism2)
return(r)
Nrow <- function(x) {
d <- dim(x)
if (length(d) == 2L)
d[1L] else as.integer(length(x) > 0L)
}
nn1 <- !is.null(N1 <- if ((l1 <- Nrow(..1)) && !ism1) Nms(1L))
nn2 <- !is.null(N2 <- if (na == 2 && Nrow(..2) && !ism2) Nms(2L))
if (nn1 || nn2 || fix.na) {
if (is.null(rownames(r)))
rownames(r) <- rep.int('', nrow(r))
setN <- function(i, nams) rownames(r)[i] <<- if (is.null(nams)) ''
else nams
if (nn1)
setN(1L, N1)
if (nn2)
setN(1L + l1, N2)
if (fix.na)
setN(nrow(r), Nna)
}
r
}
## set all NA dnn to NULL, mixture of NA/names to ''
rm_na_dimnames <- function(x, which = c('row', 'col'), rm_null = TRUE) {
nn <- rownames(x)
if (!is.null(nn) && 'row' %in% which) {
if (all(na <- is.na(nn)))
rownames(x) <- NULL
else rownames(x)[na] <- ''
}
nn <- colnames(x)
if (!is.null(nn) && 'col' %in% which) {
if (all(na <- is.na(nn)))
colnames(x) <- NULL
else colnames(x)[na] <- ''
}
if (rm_null)
if (all(sapply(dimnames(x), is.null)))
dimnames(x) <- NULL
x
}
#' @rdname bindx
#' @export
rbindfill <- function(...) {
l <- list(...)
if (length(l) == 1L)
return(..1)
nn <- lapply(l, names)
if (any(vapply(nn, is.null, NA)))
stop('\'rbindlist\' requires all vectors to be named', call. = FALSE)
un <- unique(unlist(nn))
ll <- sapply(l, length)
res <- vector('list', length(ll))
for (ii in seq_along(ll))
res[[ii]] <- unname(l[[ii]])[match(un, nn[[ii]])]
res <- do.call('rbind', res)
colnames(res) <- un
res
}
#' @rdname bindx
#' @export
rbindfill2 <- function(..., use.rownames = FALSE) {
l <- list(...)
nn <- lapply(l, colnames)
un <- unique(unlist(nn))
if (any(vapply(nn, is.null, NA))) {
warning('\'rbindfill2\' requires objects with column names\n\n',
'Returning rbindx(...)')
return(do.call('rbindx', l))
}
res <- lapply(l, function(x) {
if (!all(wh <- un %in% names(x))) {
mat <- matrix(NA, nrow = nrow(x), ncol = sum(!wh),
dimnames = list(NULL, un[!wh]))
res <- do.call('cbind', list(x, mat))
res[, un]
} else x[, un]
})
res <- do.call('rbind', res)
if (!use.rownames)
rownames(res) <- NULL
res
}
#' @rdname bindx
#' @export
rbindlist <- function(..., use.rownames = FALSE, use.names = FALSE) {
l <- if (is.list(..1))
c(...) else list(...)
if (length(l) == 1L) {
# return(..1)
names(l) <- names(l) %||% 1
l <- c(l, list(extra = NA))
l <- Recall(l, use.rownames = use.rownames, use.names = use.names)
return(head(l, -1L))
}
# nn <- if (is.null(names(l)))
# seq_along(l) else make.unique(names(l))
nn <- names(l) %||% seq_along(l)
nn <- rep(nn, vapply(l, length, integer(1L)))
res <- data.frame(idx = nn, value = unlist(l), stringsAsFactors = FALSE)
if (use.names)
res <- cbind(res, names = unlist(lapply(l, function(x)
if (is.null(nn <- names(x))) rep(NA, length(x)) else nn)))
if (!use.rownames)
rownames(res) <- NULL
res
}
#' @rdname bindx
#' @export
rbindlist2 <- function(data, column, split = '\\W+', fixed = FALSE, perl = FALSE,
use.rownames = any(rownames(data) != seq.int(nrow(data)))) {
if (missing(column) || any(column %ni% colnames(data)))
return(data)
force(use.rownames)
while (length(column) > 1L) {
data <- Recall(data, column[1L], split, fixed, perl, use.rownames)
column <- column[-1L]
}
l <- strsplit(as.character(data[, column]), split, fixed, perl)
if (all(lengths(l) == 1L)) {
message('No rows were split for column ', shQuote(column))
return(data)
}
l <- rbindlist(l, use.rownames = FALSE, use.names = FALSE)