Debian Codegraph @

R/misc-goodies.R

raw
1 #### misc-goodies.R
2 #### ~~~~~~~~~~~~~~ SfS - R - goodies that are NOT in
3 #### "/u/sfs/R/SfS/R/u.goodies.R"
4 #### "/u/sfs/R/SfS/R/p.goodies.R"
5
6 ###--- Original: From 'S' in /u/sfs/S/misc-goodies.S
7 ###--- ======== But start doing *less* here !
8
9 ###==================================================================
10 ### Functions <<<<<<<< Please use a few subsections like "Plotting"...
11 ###==================================================================
12
13 ### ___Note___ we have some of these headers __MESS__
14 ### But we leave it because of RCS {rather dismantle everything into 4-6 pieces
15
16 ## A fast substitute for structure() *when* we don't need to special case for factor, .Dim, ...
17 struct <- function(x, ...) `attributes<-`(x, c(attributes(x), list(...)))
18
19 ##' list_(a, b, cc) creates a *named* list using the actual arguments' names
20 list_ <- function(...)
21 `names<-`(list(...), vapply(sys.call()[-1L], as.character, ""))
22
23 ##-#### Vector, Matrix (or higher Array) stuff ########
24 ##-### -------------------------------------- ########
25
26 last <- function(x, length.out = 1, na.rm = FALSE)
27 {
28 ## Purpose: last element(s) of a vector
29 ## Author: Werner Stahel, Date: Tue Jan 21 17:29:42 1992
30 ## ----------------------------------------------------------------
31 ## Arguments:
32 ## x: vector
33 ## length.out: if positive, return the length.out last elements of x,
34 ## if negative, the last length.out elements are dropped
35 ## ----------------------------------------------------------------
36 if (na.rm)
37 x <- x[!is.na(x)]
38 n <- length(x)
39 x[sign(length.out)*(n-abs(length.out)+1):n]
40 }
41
42 empty.dimnames <- function(a) {
43 ## 'Remove' all dimension names from an array for compact printing.
44 n <- length(da <- dim(a))
45 if(n) dimnames(a) <- lapply(1:n, function(i) rep.int("", da[i]))
46 a
47 }
48
49
50 ##-#### Plot / Devices related stuff ########
51 ##-### ----------------------------- ########
52 ##-### >>>>> "p.goodies.S" or "ps.goodies.S" ########
53
54 errbar <- function(x, y, yplus, yminus, cap = 0.015,
55 ylim = range(y, yplus, yminus),
56 xlab = deparse(substitute(x)),
57 ylab = deparse(substitute(y)), ... )
58 {
59 ## Purpose: Makes a plot with error bars
60 ## Authors: Charles Geyer, Statistics, U. Chicago, [email protected]
61 ## Martin Maechler, Date: 11 Apr 91 and Mar 27 1992, 12:32
62 ## ----------------------------------------------------------------
63 ## Arguments: --- see help(..) page ---> ?errbar
64 ## ----------------------------------------=======
65
66 plot( x, y, ylim=ylim, xlab=xlab, ylab=ylab, ... )
67 xcoord <- par()$usr[1:2]
68 segments( x, yminus, x, yplus )
69 smidge <- cap * ( xcoord[2] - xcoord[1] ) / 2
70 segments( x - smidge, yminus, x + smidge, yminus )
71 segments( x - smidge, yplus, x + smidge, yplus )
72 }
73 ## C.Monatsname , etc.. sind jetzt bei der zugehoerigen Funktion
74 ## u.Datumvonheute in /u/sfs/S/u.goodies.S
75
76 cum.Vert.funkt <- function(x, Quartile = TRUE, titel = TRUE, Datum = TRUE,
77 rang.axis = n <= 20, xlab = "", main = "", ...)
78 {
79 ## Ziel: Kumulative Verteilung von x aufzeichnen, auf Wunsch auch Median
80 ## und Quartile
81 op <- par(xaxs = "r", yaxs = "r", las = 1)# the default anyway
82 on.exit(par(op))
83 r <- plotStep(x, xlab = xlab, main = main, ...)
84 #### FIXME : stepfun() / ecdf() instead
85 n <- length(x)
86 if(rang.axis)
87 axis(4, at = (0:n)/n, labels = 0:n, pos = par("usr")[1])#, las = 1)
88 if(titel) mtext("Kumulative Verteilungsfunktion", 3, line = 0.5)
89 if(Quartile) for(i in 1:3) abline(h = i/4, lty = 2)
90 if(Datum) p.datum()
91 invisible(r)
92 }
93
94
95 ## This was "plot.step()" but that's in conflict with S3 methods
96 plotStep <- function(ti, y,
97 cad.lag = TRUE,
98 verticals = !cad.lag,
99 left.points = cad.lag,
100 right.points = FALSE,
101 end.points = FALSE,
102
103 add = FALSE,
104
105 pch = par('pch'),
106 xlab = deparse(substitute(ti)),
107 ylab = deparse(substitute(y)),
108 main = NULL,
109 ...)
110
111 #####- FIXME ----------- use stepfun(), plot.stepfun() etc !!! ----------------
112
113 {
114 ## Purpose: plot step-function f(x)= sum{ y[i] * 1_[ t[i-1], t[i] ] (x) }
115 ## -------------------------------------------------------------------------
116 ## Arguments: for missing 'y', do empirical CDF; ==> ON-LINE Help "?plot.step"
117 ## -------------------------------------------------------------------------
118 ## Author: Martin Maechler, 1990, U.Washington, Seattle; improved -- Dec.1993
119 ##
120 ## EXAMPLE: ##-- Plot empirical cdf Fn(x) for a small n:
121 ## xx <- runif(20); plot.step(xx); plot.step( xx, cad.lag = F )
122 ## plot.step( runif(20), add=T, cad.lag=F)
123 xlab
124 ylab
125 if(missing(y)) {
126 if(is.vector(ti) && is.numeric(ti)) { # -- Do empirical CDF --
127 nt <- length(ti)
128 ti <- sort(ti)
129 dt <- (ti[nt] - ti[1])/20
130 ti <- c(ti[1] - dt, ti, ti[nt] + dt)
131 n <- nt + 1
132 y <- (0:nt)/nt
133 } else {
134 xy <- xy.coords(ti,NULL,NULL,NULL)
135 ti <- c(xy$x[1], xy$x)
136 y <- xy$y
137 n <- length(y)
138 }
139 } else {
140 n <- length(y)
141 if(length(ti) != (n + 1)) stop("length(ti) MUST == length(y) + 1")
142 }
143 if(length(ti) != (n + 1) || length(y) != n)
144 stop("NEVER CALLED! --length(ti) MUST == length(y) + 1")
145 if(missing(main)) main <- deparse(sys.call())
146
147 n1 <- n+1
148 ##-- horizontal segments:
149 if (add) segments(ti[-n1], y, ti[-1], y, ...)
150 else {
151 plot(ti, c(y[1],y), type = 'n', xlab = xlab, ylab = ylab, main = main, ...)
152 segments(ti[-n1], y, ti[-1], y)
153 }
154 if(left.points) points(ti[-n1],y, pch = pch)
155 if(right.points) points(ti[-1], y, pch = pch)
156 ##-- col=0 <==> "erase" :
157 if(! end.points) points(ti[c(1,n1)], y[c(1,n)], pch = pch, col = 0)
158 if(verticals) {
159 if (add) segments(ti[2:n], y[-n], ti[2:n], y[-1], ...)
160 else segments(ti[2:n], y[-n], ti[2:n], y[-1])
161 }
162 invisible(list(t = ti, y = y))
163 }
164
165 histBxp <-
166 function(x, nclass, breaks, probability = FALSE, include.lowest = TRUE,
167 xlab = deparse(substitute(x)), ..., width = 0.2,
168 boxcol = 3, medcol = 2, medlwd = 5, whisklty = 2, staplelty = 1)
169 {
170 ## Purpose: Plot a histogram and a boxplot
171 ## -------------------------------------------------------------------------
172 ## Arguments: ---> see help(hist.bxp) !
173 ## -------------------------------------------------------------------------
174 ## Authors: Christian Keller, Date: 10 Nov 95, (Martin Maechler, Jan 96)
175 ## calls p.hboxp(.) !
176
177 ## determine the height of the plot
178 h <-
179 if(missing(breaks)){
180 if(missing(nclass))
181 hist(x, include.lowest = include.lowest, plot = FALSE)
182 else
183 hist(x, nclass = nclass,
184 include.lowest = include.lowest, plot = FALSE)
185 }
186 else
187 hist(x, breaks = breaks,
188 include.lowest = include.lowest, plot = FALSE)
189 ymax <- max(h$counts)
190 ymin <- - ymax * width # range: (-w,1)*ymax instead of (0,1)*ymax
191
192 ##------- drawing the histogram -------------
193 hist(x, breaks = h$breaks, probability = probability,
194 include.lowest = include.lowest, plot = TRUE, xlab = xlab,
195 ylim = c(ymin, ymax), axes = FALSE, ...)
196 axis(1)
197 axis(2, at = pretty(c(0,ymax), n = 5), srt = 90) ## ph, 8.5.00: n instead of nint
198 abline(h = 0) #
199 ##-------- drawing the boxplot --------------
200
201 ##-- scale a range
202 scale.r <- function(x1,x2, fact = 1.1)
203 (x1+x2)/2 + c(-fact,fact) * (x2-x1)/2
204
205 ##-- since 4% extra space above x-axis (just below ymin):
206 ##- cat("par$usr[3:4]:", par("usr")[3:4],
207 ##- " ymin -.04 *(ymax-ymin)",ymin -.04 *(ymax-ymin),"\n")
208 ##-- NOTE: Always have (seemingly): par("usr")[3] == ymin -.04 *(ymax-ymin)
209
210 ##-O- ORIGINAL VERSION (Keller & Keller) :
211 ##-O- p.hboxp(x, ymin, -.04 *(ymax-ymin),
212 ##-O- boxcol=boxcol, medcol=medcol,
213 ##-O- medlwd=medlwd, whisklty=whisklty, staplelty=staplelty)
214
215 ##---- This is much better for width <=.1 or so...
216 ##-- but you should leave some white space -> scale down
217 ##-- The scaling factor is really a KLUDGE but works for a wide range!
218 p.hboxp(x, scale.r(par("usr")[3], 0, ## ph, 8.5.00: changed f=.9 to f=.8
219 fact = .8 - max(0, .15 - width)*(1+(par("mfg")[3] >= 3))),
220 boxcol = boxcol, medcol = medcol,
221 medlwd = medlwd, whisklty = whisklty, staplelty = staplelty)
222 }
223
224
225 ##-#### Print & Strings ########
226 ##-### =============== ########
227
228 ccat <- ## character 'concat'
229 function(...) paste0(..., collapse = "")
230 vcat <- ## (numeric) vector 'concat'
231 function(vec, sep = " ") paste(vec, collapse = sep)
232
233 paste.vec <- function(name, digits = options()$digits)
234 {
235 ## Purpose: Utility for "showing vectors"
236 ## -------------------------------------------------------------------------
237 ## Example: x <- 1:4; paste.vec(x) ##-> "x = 1 2 3 4"
238 paste(paste(deparse(substitute(name))), "=",
239 paste(format(name, digits = digits), collapse = " "))
240 }
241 signi <- function(x, digits = 6) round(x, digits - trunc(log10(abs(x))))
242
243 ##' NB: Since ~ R 3.3.0 (May 2016), use base R's "new" strrep(x, times) instead
244
245 repChar <- function(char, no) paste(rep.int(char, no), collapse = "")
246 ## correct, but slower than the next one:
247 bl.string <- function(no) repChar(" ", no)
248 ## faster:
249 bl.string <- function(no) sprintf("%*s", no, "")
250
251 ### symnum : standard R function !!
252
253 wrapFormula <- function(f, data, wrapString = "s(*)")
254 {
255 ## Purpose: Mainly: Construct a useful gam() formula from "Y ~ ."
256 ## ----------------------------------------------------------------------
257 ## Arguments: f : the initial formula; typically something like "Y ~ ."
258 ## data: data.frame to which the formula applies
259 ## ----------------------------------------------------------------------
260 ## Author: Martin Maechler, Date: 22 May 2007, 18:03
261
262 form <- formula(terms(f, data = data))
263 if(length(form) != 3)
264 stop("invalid formula; need something like 'Y ~ .'")
265 wrapS <- strsplit(wrapString, "\\*")[[1]]
266 stopifnot(length(wrapS) == 2)
267 cc <- gsub("([^+ ]+)", paste0(wrapS[1], "\\1", wrapS[2]),
268 format(form[[3]]))
269 form[[3]] <- parse(text = cc, srcfile = NULL)[[1]]
270 form
271 }
272
273 ##' Capture Output and print first and last parts, eliding middle parts.
274 ##' Particularly useful for teaching purposes, and e.g., in Sweave
275 ##'
276 ##' @title Capture output and Write / Print First and Last Parts
277 ##' @param EXPR the (literal) expression the output is to be captured
278 ##' @param first integer: how many lines should be printed at beginning
279 ##' @param last integer: how many lines should be printed at the end.
280 ##' @param middle numeric (or NA logical):
281 ##' @param i.middle index start of middle part
282 ##' @param dotdots string to be used for elided lines
283 ##' @param n.dots number of \code{dotdots} ....{FIXME}
284 ##' @return return value of \code{\link{capture.output}(EXPR)}
285 ##' @author Martin Maechler
286 ## -> ../man/capture-n-write.Rd
287 capture.and.write <- function(EXPR, first, last = 2,
288 middle = NA, i.middle,
289 dotdots = " ....... ", n.dots = 2) {
290 co <- capture.output(EXPR)
291 writeLines(head(co, first))
292 catDots <- function(M) cat(rep.int(paste0(dotdots,"\n"), M), sep="")
293 catDots(n.dots)
294 if(is.numeric(middle)) {
295 stopifnot(length(middle) == 1, middle >= 0, middle == round(middle))
296 i0 <- first+2
297 if(missing(i.middle)) {
298 i.middle <- max(i0, length(co) %/% 2 - middle %/% 2)
299 } else { ## !missing(i.middle)
300 if(i.middle < i0)
301 stop("'i.middle' is too small, should be at least ", i0)
302 }
303 writeLines(co[i.middle-1 + seq_len(middle)])
304 catDots(n.dots)
305 }
306 writeLines(tail(co, last))
307 invisible(co)
308 }
309
310
311
312 ##-#### "Calculus" Mathematical stuff ########
313 ##-### ----------------------------- ########
314
315 polyn.eval <- function(coef, x)
316 {
317 ## Purpose: compute coef[1] + coef[2]*x + ... + coef[p+1]* x^p
318 ## if coef is vector, x can be any array; result : of same dim. as x
319 ## if coef is matrix, x must be vector; dim(result) = len(x) * nrow(coef)
320 ## coef = matrix: evaluate SEVERAL polynomials (of same degree)
321 ## ---- contains coefficient-vectors as ROWS ==> coef[,i] <-> x^{i-1}
322 ## Author: Martin Maechler <[email protected]>
323 if(is.null(dim(coef))) {
324 lc <- length(coef)
325 if (lc == 0L) 0
326 else {
327 r <- coef[lc]
328 if (lc == 1L)
329 r + 0*x # keep dim(x)
330 else { # lc > 1
331 for (i in (lc-1):1) r <- coef[i] + r*x
332 r
333 }
334 }
335 } else { #-- coef is MATRIX --
336 dc <- dim(coef)
337 lc <- dc[2]; dc <- dc[1]
338 n <- length(x)
339 if (lc == 0) matrix(0, n, dc) else {
340 r <- matrix(coef[,lc], n, dc, byrow = TRUE)
341 if (lc > 1)
342 for (i in (lc-1):1) r <- r*x + matrix(coef[,i], n, dc, byrow = TRUE)
343 r
344 }
345 }
346 }
347
348 ## negative x .. may make sense in some cases,.... but not yet :
349 ##digitsBase <- function(x, base = 2, ndigits = 1 + floor(log(max(abs(x)),base)))
350 digitsBase <- function(x, base = 2, ndigits = 1 + floor(1e-9 + log(max(x,1), base)))
351 {
352 ## Purpose: Give the vector A of the base-_base_ representation of _n_:
353 ## ------- n = sum_{k=0}^M A_{M-k} base ^ k , where M = length(a) - 1
354 ## Value: MATRIX M where M[,i] corresponds to x[i]
355 ## Author: Martin Maechler, Date: Dec 4, 1991
356 ## ----------------------------------------------------------------
357 ## ----> help(digitsBase) !
358 ## ------------------------------
359 if(any(x < 0))
360 stop("'x' must be non-negative integers")
361 if(any(x != trunc(x)))
362 stop("'x' must be integer-valued")
363 r <- matrix(0, nrow = ndigits, ncol = length(x))
364 if(ndigits >= 1) for (i in ndigits:1) {
365 r[i,] <- x %% base
366 if (i > 1) x <- x %/% base
367 }
368 class(r) <- "basedInt"
369 attr(r, "base") <- base
370 r
371 }
372
373 bi2int <- function(xlist, base)
374 vapply(xlist, function(u) polyn.eval(rev(u), base), numeric(1))
375
376 as.intBase <- function(x, base = 2) {
377 xl <- if(is.character(x)) lapply(strsplit(x,""), as.integer)
378 else if(is.numeric(x) && is.matrix(x)) tapply(x, col(x), c)
379 else if(!is.list(x))
380 stop("'x' must be character, list or a digitsBase() like matrix")
381 bi2int(xl, base)
382 }
383
384 as.integer.basedInt <- function(x, ...)
385 as.intBase(x, base = attr(x, "base"))
386
387 print.basedInt <- function (x, ...) {
388 cat(sprintf("Class 'basedInt'(base = %d) [1:%d]\n",
389 attr(x,"base"), ncol(x)))
390 cx <- x
391 attr(cx,"base") <- NULL
392 print(unclass(cx), ...)
393 invisible(x)
394 }
395
396 sHalton <- function(n.max, n.min = 1, base = 2, leap = 1)
397 {
398 ## Purpose: Halton sequence H(k,b) for k=n.min:n.max -- for Quasi Monte Carlo
399 ## ----------------------------------------------------------------------
400 ## Author: Martin Maechler, Date: 29 Jul 2004, 21:34
401
402 stopifnot((leap <- as.integer(leap)) >= 1)
403 ## now do this via digitsBase(), later go directly
404 nd <- as.integer(1 + log(n.max, base))
405 dB <- digitsBase(if(leap == 1) n.min:n.max else seq(n.min, n.max, by=leap),
406 base = base, ndigits = nd)
407 colSums(dB/base^(nd:1))
408 }
409
410 QUnif <- function(n, min = 0, max = 1, n.min = 1, p, leap = 1, silent = FALSE)
411 {
412 ## Purpose: p-dimensional ''Quasi Random'' sample in [min,max]^p
413 ## ----------------------------------------------------------------------
414 ## Author: Martin Maechler, Date: 29 Jul 2004, 21:43
415 ## Example: plot(QUnif(1000, 2), cex=.6, pch=20, xaxs='i', yaxs='i')
416 stopifnot(1 <= (n <- as.integer(n)), length(n) == 1,
417 1 <= (p <- as.integer(p)), length(p) == 1,
418 length(min) == p || length(min) == 1,
419 length(max) == p || length(max) == 1,
420 1 <= (n.min <- as.integer(n.min)),
421 1 <= (leap <- as.integer(leap)),
422 (n.max <- n.min + (n - 1:1)*leap) < .Machine$integer.max)
423 pr. <- c(2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,
424 89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,
425 179,181,191, 193,197,199,211,223,227,229,233,239,241,251,257,263,
426 269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,
427 367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457)
428 if(length(pr.) < p) {
429 if(!silent)
430 message("enlarging internal prime table for \"large\" p=",p)
431 Lp <- log(p)
432 pr. <- primes(p*(Lp + log(Lp))) ## using p_n/n < log n + log log n
433 }
434 pr <- pr.[1:p]
435 if(leap > 1 && any(leap == pr) && length(pr.) >= p+1) # take a non-leap pr
436 pr <- c(pr[leap != pr], pr.[p+1])
437 max <- rep.int(max, p)
438 min <- rep.int(min, p)
439 dU <- max - min
440 r <- matrix(0., n, p)
441 for(j in 1:p)
442 r[,j] <- min[j] + dU[j] *
443 sHalton(n.max, n.min, base = pr[j], leap = leap)
444 r
445 }
446
447
448
449 chars8bit <- function(i = 1:255)
450 {
451 ## Purpose: Compute a character vector from its "ASCII" codes.
452 ## We seem to have to use this complicated way thru text and parse.
453
454 ## Author: Martin Maechler, Original date: Wed Dec 4, 1991
455 ## this is an improved version of make.ASCII() from ~/S/Good-string.S !
456 ## ----------------------------------------------------------------
457 i <- as.integer(i)
458 if(any(i < 0 | i > 255)) stop("'i' must be in 0:255")
459 if(any(i == 0))
460 warning("\\000 (= 'nul') is no longer allowed in R strings")
461 i8 <- apply(digitsBase(i, base = 8), 2, paste, collapse="")
462 c8 <- paste0('"\\', i8, '"')
463 eval(parse(text = paste0("c(",paste(c8, collapse=","),")")))
464 }
465
466 strcodes <- function(x, table = chars8bit(1:255))
467 {
468 ## Purpose: R (code) implementation of old S's ichar()
469 ## ----------------------------------------------------------------------
470 ## Arguments: x: character vector
471 ## ----------------------------------------------------------------------
472 ## Author: Martin Maechler, Date: 23 Oct 2003, 12:42
473
474 lapply(strsplit(x, ""), match, table = table)
475 }
476
477 ## S-PLUS has AsciiToInt() officially, and ichar() in library(examples):
478 AsciiToInt <- ichar <- function(strings) unname(unlist(strcodes(strings)))
479
480 helppdf <- function(topic, viewer = getOption("pdfviewer"), quiet = !interactive(),
481 ...) {
482 if(!tryCatch(is.character(topic) && length(topic) == 1L,
483 error = function(e) FALSE))
484 topic <- deparse1(substitute(topic))
485 hh <- help(topic, help_type = "pdf", ...)
486 pdfile <- with(attributes(hh), paste(topic, type, sep="."))
487 ## almost all rendering & pdf creation happens here:
488 print(hh, msg=!quiet)# utils:::print.help_files_with_topic() |--> .show_help_on_topic_offline(<texf>, ..)
489 # ~~~~~~~~~~~~~~~~~~~~~~~~~~~ ..........
490 if(length(viewer))
491 system(paste(viewer, pdfile), wait = FALSE)
492 ans <- file.path(getwd(), pdfile)
493 if(quiet) invisible(ans) else ans
494 }
495
496
497
498
499 ##-#### "Miscellaneous" (not any other category) ########
500 ##-### ============= ------------------------- ########
501
502 uniqueL <- function(x, isuniq = !duplicated(x), need.sort = is.unsorted(x))
503 {
504 ## return list(ix, uniq)
505 ## such that all(x == uniq[ix]) and (of course) uniq == x[isuniq]
506 if(need.sort) {
507 xs <- sort(x, index.return = TRUE)
508 ixS <- xs $ ix
509 isuniq <- isuniq[ixS]
510 x <- xs$x
511 }
512 ix <- as.integer(cumsum(isuniq))
513 if(need.sort)
514 ix <- ix[sort.list(ixS)]
515 list(ix = ix, xU = x[isuniq])
516 }
517
518
519 ##' Constructor of a "list" (really an environment) of functions (and more)
520 ##' which all *share* the same environment in which they exist
521 ##' --> ../man/funEnv.Rd
522 ##' ~~~~~~~~~~~~~~~~
523 funEnv <- function(..., envir = NULL, parent = parent.frame(),
524 hash = (...length() > 100), size = max(29L, ...length())) {
525 e <- list2env(list(...), envir=envir, parent=parent, hash=hash, size=size)
526 for(n in names(e)) ## iff function or formula, set environment to 'e':
527 if(is.function(e[[n]]) || (is.call(e[[n]]) &&
528 inherits(e[[n]], "formula")))
529 environment(e[[n]]) <- e
530 e
531 }
532
533
534 is.whole <- function(x, tolerance = sqrt(.Machine$double.eps))
535 {
536 ## Tests if a numeric scalar (or vector, matrix or array) is a whole
537 ## number; returns an boolean object of the same dimension as x, each entry
538 ## indicating whether the corresponding entry in x is whole.
539 is.whole.scalar <-
540 if (is.integer(x)) {
541 function(x) TRUE
542 } else if (is.numeric(x)) {
543 function(x) isTRUE(all.equal(x, round(x), tolerance = tolerance))
544 } else if (is.complex(x)) {
545 function(x)
546 isTRUE(all.equal(Re(x), round(Re(x)), tolerance = tolerance)) &&
547 isTRUE(all.equal(Im(x), round(Im(x)), tolerance = tolerance))
548 } else stop("Input must be of type integer, numeric or complex.")
549
550 if (is.null(dim(x)))
551 vapply(x, is.whole.scalar, NA)
552 else
553 apply(x, seq_along(dim(x)), is.whole.scalar)
554 }
555
556 ##'
557 ##' @title Generate Random Date/Time Sequences
558 ##' @param n number of entries to generate
559 ##' @param min, max character strings or \R objects inheriting from \code{"POSIXt"}.
560 ##' @return vector
561 ##' @author Martin Maechler
562 ##
563 ## __ NOT YET EXPORTED
564 ## FIXME: consider 'mean = Sys.time(), delta.tim = "1 month"'
565 ## ----- ==> min = mean - as.difftime(delta.tim),
566 ## max = mean - as.difftime(delta.tim)
567 ## now <- Sys.time(); del <- as.difftime(100, units="weeks")
568 ## rDatetime(100, now-del, now+del)
569 rDatetime <- function(n, min = "1900-01-01", max = "2100-12-31") {
570 if(is.character(min) || inherits(min, "POSIXt"))
571 min <- as.POSIXct(min)
572 else stop("'min' must be string (coercable to \"POSIXct\") or \"POSIXt\" object")
573 if(is.character(max) || inherits(max, "POSIXt"))
574 max <- as.POSIXct(max)
575 else stop("'max' must be string (coercable to \"POSIXct\") or \"POSIXt\" object")
576 stopifnot(length(min) == 1, length(max) == 1)
577 struct(runif(n, as.numeric(min), as.numeric(max)),
578 class = c("POSIXct", "POSIXt"), tzone = "")
579 }
580
581 ###
582 ### autoreg(), mean.cor() etc ... not yet
583 ###
584 ### if we take them, use different file !!
585
586
587
588 ####========== This is from /u/maechler/S/Good.S =============
589 ####========== --------------------------------- =============
590
591 ##-#### Plot / Devices related stuff ########
592 ##-### ----------------------------- ########
593
594 mpl <- function(mat, ...) {
595 matplot(1:nrow(mat), mat, xaxt = 'n',...)
596 if(0 == length(dn <- dimnames(mat)[[1]]))
597 axis(1) else
598 axis(1, at = 1:nrow(mat), labels = dn)
599 }
600
601 roundfixS <- function(x, method = c("offset-round", "round+fix", "1greedy"))
602 {
603 ## Purpose: y := r2i(x) with integer y *and* sum(y) == sum(x)
604 ## Author: Martin Maechler, 28 Nov 2007
605 n <- length(x)
606 x0 <- floor(x)
607 e <- x - x0 ## == (x %% 1) in [0, 1)
608 S. <- sum(e)
609 stopifnot(all.equal(S., (S <- round(S.))))
610 method <- match.arg(method)
611
612 ## The problem is equivalent to transforming
613 ## e[] \in [0,1) into f[] \in {0,1}, with sum(e) == sum(f)
614 ## Goal: transform e[] into f[] gradually, by "shifting" mass
615 ## such that the sum() remains constant
616
617 switch(method,
618 "offset-round" = {
619 ## This is going to be equivalent to
620 ## r := round(x + f) with the correct f \in [-1/2, 1/2], or
621 ## r == floor(x + f + 1/2) = floor(x + g), g \in [0, 1]
622 ##
623 ## Need sum(floor(e + g)) = S;
624 ## since sum(floor(e)) == 0, sum(floor(e+1)) == n,
625 ## we just need to floor(.) the S smallest, and ceiling(.) the others
626 if(S > 0) {
627 r <- numeric(n) # all 0; set to 1 those corresponding to large e:
628 r[sort.list(e, decreasing=TRUE)[1:S]] <- 1
629 x0 + r
630 } else x
631 }, ## end{offset-round}
632
633 "round+fix" = {
634 r <- round(e)
635 if((del <- S - sum(r)) != 0) { # need to add +/- 1 to 'del' entries
636 s <- sign(del) ## +1 or -1: add +1 only to r < x entries,
637 aD <- abs(del) ## and -1 only to r > x entries,
638 ## those with the "worst" rounding are made a bit worse
639 if(del > 0) {
640 iCand <- e > r
641 dx <- (e - r)[iCand] # > 0
642 } else { ## del < 0
643 iCand <- e < r
644 dx <- (e - x)[iCand] # > 0
645 }
646 ii <- sort.list(dx, decreasing = TRUE)[1:aD]
647 r[iCand][ii] <- r[iCand][ii] + s
648 }
649
650 return(x0 + r)
651
652 }, ## end{round+fix}
653
654 "1greedy" = {
655 ii <- e != 0
656 while(any(ii)) {
657 ci <- cumsum(ii) # used to revert u[ii] subsetting
658 m <- length(e. <- e[ii])
659 ie <- sort.list(e.) # both ends are relevant
660 left <- e.[ie[1]] < 1 - e.[ie[m]]
661 iThis <- if(left) 1 else m
662 iother <- if(left) m else 1
663 J <- which.max(ci == ie[iThis]) ## which(.)[1] but faster
664 I <- which.max(ci == ie[iother])
665 r <- x[J]
666 x[J] <- k <- if(left) floor(r) else ceiling(r)
667 mass <- r - k # if(left) > 0 else < 0
668 if(m <= 2) { # short cut and evade rounding error
669 if(m == 1) { # should happen **rarely**
670 if(!(min(abs(mass), abs(1-mass)) < 1e-10))
671 warning('m==1 in "1greedy" w/ mass not close to {0,1}')
672 } else { ## m==2
673 x[I] <- round(x[I] + mass)
674 }
675 break ## ii <- FALSE
676 }
677 else { ## m >= 3
678 e[J] <- if(left) 0 else 1
679 ii[J] <- FALSE
680 ## and move it's mass to the other end:
681 e.new <- e[I] + mass
682 if(e.new > 1)
683 stop("e[I] would be > 1 -- internal error")
684 else if(e.new < 0)
685 stop("e[I] would be < 0 -- internal error")
686 x[I] <- x[I] + mass
687 e[I] <- e.new
688 } ## m >= 3
689 } ## end{while}
690 x
691
692 }) # end{switch}
693 }## roundfixS
694
695
696 seqXtend <- function(x, length., method = c("simple","aim","interpolate"),
697 from = NULL, to = NULL)
698 {
699 ## Purpose: produce a seq(.) covering the range of 'x' and INCLUDING x
700 ## Author: Martin Maechler, Date: 28 Nov 2007 =======> ../man/seqXtend.Rd
701 x <- unique(sort(x))
702 n <- length(x)
703 method <- match.arg(method)
704 if(length. > n) {
705 if((from_is1 <- is.null(from))) from <- x[1]
706 if((from_isL <- is.null(to))) to <- x[n]
707 if(method == "interpolate") {
708 if(!from_is1) {
709 if(from > x[1])
710 stop("'from' > min(x) not allowed for method ", method)
711 x <- c(from, x)
712 }
713 if(!from_isL) {
714 if(to < x[n])
715 stop("'to' < max(x) not allowed for method ", method)
716 x <- c(x, to)
717 }
718 n <- length(x)
719 dx <- x[-1] - x[-n] ## == diff(x)
720 w <- as.numeric(x[n] - x[1]) ## == sum(dx);
721 ## as.n..(.) -> works with "Date" etc
722 nn <- length. - n ## need 'nn' new points in 'n - 1' intervals
723 ## how many in each?
724 ## Want them approximately equidistant, ie. of width ~= w / (nn + 1)
725 ## but do this smartly such that dx[i] / (k1[i] + 1) {= stepsize in interval i}
726 ## is approximately constant
727 k1 <- (nn + n-1) * dx / w - 1 ## ==> sum(k1) == nn
728 ## now "round" the k1[] such that sum(.) remains == nn
729 k <- roundfixS(k1) ## keep the right border, drop the left
730 seqI <- function(i) seq(x[i], x[i+1], length.out=k[i]+2)[-1]
731 l.seq <- lapply(1:(n-1), seqI)
732 ## do.call(c, *), e.g. for new (R-devel 4.1.x) c.Date() [KH]:
733 c(x[1], if(is.object(x)) do.call(c, l.seq) else unlist(l.seq))
734 } else {
735 nn <- switch(method, "simple" = length.,
736 "aim" = length. - n + from_is1 + from_isL)
737 ## a more sophisticated 'method' would have to use iteration, *or*
738 ## interpolate between the 'x' values instead
739 ## which might be considered to be too far from seq()
740 unique(sort(c(x, seq(from, to, length.out = nn))))
741 }
742 } else x
743 }## {seqXtnd}
744
745 plotDS <-
746 function(x, yd, ys, xlab = "", ylab = "", ylim = rrange(c(yd, ys)),
747 xpd = TRUE, do.seg = TRUE, seg.p = .95,
748 segP = list(lty = 2, lwd = 1, col = 2),
749 linP = list(lty = 1, lwd = 2.5, col = 3), ...)
750 {
751 ## Purpose: Plot Data & Smooth
752 ## -------------------------------------------------------------------------
753 ## Arguments: do.seg: logical, plot "residual segments" iff T (= default).
754 ## -------------------------------------------------------------------------
755 ## Author: Martin Maechler, 1990-1994
756 ## 2007: allow ys to be a (xs,ys)-xycoords structure, where {x[] \in xs[]}
757 if((hasMoreSmooth <- !is.numeric(ys))) {
758 ysl <- xy.coords(ys)
759 ixs <- match(x, ysl$x)
760 if(any(is.na(ixs)))
761 stop("'x' inside the 'ys' structure must contain all the observational 'x'")
762 ys <- ysl$y[ixs]
763 }
764 if(is.unsorted(x)) {
765 i <- sort.list(x)
766 x <- x[i]
767 yd <- yd[i]
768 ys <- ys[i]
769 }
770 addDefaults <- function(listArg) {
771 ## trick such that user can call 'segP = list(col = "pink")' :
772 nam <- deparse(substitute(listArg))
773 P <- as.list(formals(sys.function(sys.parent()))[[nam]])[-1] # w/o "list"
774 for(n in names(listArg)) P[[n]] <- listArg[[n]]
775 P
776 }
777
778 plot(x, yd, xlab = xlab, ylab = ylab, ylim = ylim, ...) #pch = pch,
779 if(!missing(linP))
780 linP <- addDefaults(linP)
781 if(hasMoreSmooth)
782 lines(ysl, xpd = xpd, lty = linP$lty, lwd = linP$lwd, col = linP$col)
783 else lines(x, ys, xpd = xpd, lty = linP$lty, lwd = linP$lwd, col = linP$col)
784 if(do.seg) {
785 if(!missing(segP))
786 segP <- addDefaults(segP)
787 segments(x, seg.p*ys + (1-seg.p)*yd, x, yd,
788 xpd = xpd, lty = segP$lty, lwd = segP$lwd, col = segP$col)
789 }
790 invisible()
791 }
792
793
794
795 ##-#### Matrix (or higher Array) stuff ########
796 ##-### ------------------------------ ########
797
798 colcenter <- function(mat) sweep(mat,2, apply(mat,2,mean))
799
800 col01scale <- function(mat, scale.func = function(x) diff(range(x)),
801 location.func = mean)
802 {
803 ##-- See also 'scale' (std. S func) --
804 mat <- sweep(mat,2, apply(mat,2, location.func))
805 sweep( mat, 2, apply(mat,2, scale.func), "/")
806 }
807
808 ## diag.ex <- function(n) --- now renamed :
809 diagX <- function(n)
810 {
811 ## Purpose: Returns "the other diagonal" matrix
812 ## Author: Martin Maechler, Date: Tue Jan 14 1992; Nov.2002
813 ## ----------------------------------------------------------------
814 ## Arguments: n: integer dimension of matrix
815 ## ----------------------------------------------------------------
816 m <- numeric(n * n)
817 m[1L+ (n-1L)* seq_len(n)] <- 1
818 dim(m) <- c(n,n)
819 m
820 }
821
822 xy.grid <- function(x,y)
823 {
824 ## Purpose: Produce the grid used by persp, contour, .. as N x 2 matrix
825 nx <- length(x)
826 ny <- length(y)
827 cbind(rep.int(x,rep.int(ny,nx)), rep.int(y,nx))
828 }
829
830 rot2 <- function(xy, phi)
831 {
832 ## Purpose: rotate xy-points by angle 'phi' (in radians)
833 ## -------------------------------------------------------------------------
834 ## Arguments: xy : n x 2 matrix; phi: angle (in [0, 2pi])
835 ## -------------------------------------------------------------------------
836 ## Author: Martin Maechler, Date: 26 Oct 94, 22:16
837 co <- cos(phi); s <- sin(phi)
838 xy %*% t( matrix(c(co,s, -s, co), 2,2) )
839 }
840
841 tapplySimpl <- function(X, INDEX, FUN, ...)
842 {
843 ## Purpose: Nicer result for tapply(..) when Function returns
844 ## vector AND there is >= 2 "INDEX", i.e., categories.
845 ## -------------------------------------------------------------------------
846 ## Arguments: as for tapply,
847 ## FUN: Must return [named, if possible] FIXED length vector
848 ## [num/char] EVEN for NULL and NA !
849 ## -------------------------------------------------------------------------
850 ## Author: Martin Maechler, Date: 14 Jun 93, 17:34
851 rl <- tapply(X, INDEX, FUN, ..., simplify = TRUE)
852 if (is.list(rl)) { #-- when >=2 indices AND length(FUN(x)) > 1 ---
853 if(any(Nas <- unlist(lapply(rl, is.null))))
854 rl[Nas] <- list(FUN(NULL))
855 array(unlist(rl),
856 dim = c(length(rl[[1]]), dim(rl)),
857 dimnames = c(list(names(rl[[1]])), dimnames(rl)) )
858 } else rl
859 }
860
861
862 ##-#### "Calculus" Mathematical stuff ########
863 ##-### ----------------------------- ########
864
865 u.log <- function(x, c = 1)
866 {
867 ## Purpose: log(.) only for high x- values ... identity for low ones
868 ## This f(x) is continuously differentiable (once).
869 ## f(x) = x for |x| <= c
870 ## f(x) = sign(x)*c*(1 + log(|x|/c)) for |x| >= c
871 ## -------------------------------------------------------------------------
872 ## Arguments: x: numeric vector; c: scalar > 0
873 ## -------------------------------------------------------------------------
874 ## Author: Martin Maechler, Date: 24 Jan 95, 17:28
875 if(!is.numeric(c)|| c < 0) stop("'c' must be positive number")
876 r <- x
877 to.log <- abs(x) > c ; x <- x[to.log]
878 r[to.log] <- sign(x) * c * (1 + log(abs(x/c)))
879 r
880 }
881
882 xy.unique.x <- function(x, y, w, fun.mean = mean, ...)
883 {
884 ## Purpose: given 'smoother data' (x_i, y_i) [and maybe weight w_i]
885 ## with multiple x_i, use unique x's, replacing y's by their mean
886 ## -------------------------------------------------------------------------
887 ## Author: Martin Maechler, Date: 8 Mar 93, 16:36
888 ##--*--*--*--*--*--*--*--*--*-- x,y,w treatment --*--*--*--*--*--*--*--*--
889 if(missing(x)) x <- time(y) else
890 if(missing(y)) {
891 if(is.list(x)) {
892 if(any(is.na(match(c("x", "y"), names(x)))))
893 stop("cannot find x and y in list")
894 y <- x$y; x <- x$x; if(!is.null(x$w)) w <- x$w
895 } else if(is.complex(x)) {
896 y <- Im(x); x <- Re(x)
897 } else if(is.matrix(x) && ncol(x) == 2) {
898 y <- x[, 2]; x <- x[, 1]
899 } else if(is.matrix(x) && ncol(x) == 3) {
900 y <- x[, 2]; w <- x[, 3]; x <- x[, 1]
901 } else {
902 y <- x; x <- time(x)
903 }
904 }
905 n <- length(x)
906 if(n != length(y)) stop("lengths of x and y must match")
907 if(missing(w)) w <- rep.int(1,n)
908 else if(n != length(w)) stop("lengths of x and w must match")
909 ##--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--
910 gr <- match(x, ux <- unique(x, ...))
911 cbind(x = ux,
912 y = tapply(y, gr, FUN = fun.mean),
913 w = tapply(w, gr, FUN = sum))
914 }
915
916
917
918 ##-#### Non-calculus ("Discrete") Mathematical stuff ########
919 ##-### -------------------------------------------- ########
920
921 lseq <- function(from, to, length)
922 {
923 ## Purpose: seq(.) : equidistant on log scale
924 ## ----------------------------------------------------------------------
925 ## Author: Martin Maechler, Date: 3 Feb 2005, 08:34
926 stopifnot(from > 0)
927 exp(seq(log(from), log(to), length.out = length))
928 }
929
930 inv.seq <- function(i) {
931 ## Purpose: 'Inverse seq': Return a short expression for the 'index' 'i'
932 ## --------------------------------------------------------------------
933 ## Arguments: i: vector of (usually increasing) integers.
934 ## --------------------------------------------------------------------
935 ## Author: Martin Maechler, Date: 3 Oct 95, 18:08
936 ## --------------------------------------------------------------------
937 ## EXAMPLES: cat(rr <- inv.seq(c(3:12, 20:24, 27, 30:33)),"\n"); eval(rr)
938 ## r2 <- inv.seq(c(20:13, 3:12, -1:-4, 27, 30:31)); eval(r2); r2
939 li <- length(i <- as.integer(i))
940 if(li == 0) return(expression(NULL))
941 else if(li == 1) return(as.expression(i))
942 ##-- now have: length(i) >= 2
943 di1 <- abs(diff(i)) == 1 #-- those are just simple sequences n1:n2 !
944 i <- i + 0 # coercion to "double", so result has no 'L' appended integers.
945 s1 <- i[!c(FALSE,di1)] # beginnings
946 s2 <- i[!c(di1,FALSE)] # endings
947 mkseq <- function(i, j) if (i==j) i else call(':', i, j)
948 as.call(c(list(as.name('c')),
949 mapply(s1, s2, FUN=mkseq, SIMPLIFY=FALSE, USE.NAMES=FALSE)))
950 }
951
952 iterate.lin.recursion <- function(x, coeff, delta = 0, nr.it)
953 {
954 r <- c(x, numeric(nr.it))
955 n <- length(x)
956 ic <- length(coeff):1
957 for(i in 1:nr.it)
958 r[n + i] <- delta + c(coeff %*% r[n + i - ic])
959 r
960 }
961
962 quadrant <- function(x,y=NULL) {
963 xy <- xy.coords(x,y); x <- xy$x; y <- xy$y
964 Sgn <- function(u) ifelse(u >= 0, 1, -1)
965 y <- Sgn(y); 2 - y + (y != Sgn(x))
966 }
967
968 n.code <- function(n, ndig = 1, dec.codes = c("","d","c","k"))
969 {
970 ##-- convert "round integers" to short char.strings
971 ##-- useful to build-up variable names in simulations
972 ##-- e.g.,
973 nd <- length(dec.codes)
974 e10 <- pmin(floor(log10(n) + 1e-12), nd - 1)
975 if (any(e10 < 0)) {
976 e10 <- pmax(0, e10) ; warning("some 'n' too small")
977 }
978 ## IDEA: Things like
979 ## ---- n.code(c(2000,1e4,5e4,6e5,7e6,8e7),
980 ## dec. = c("","d","c","k","-","-","M"))
981 ## could work; (not quite yet, see ex. above)
982 ##- if(any(id <- is.na(dec.codes) | dec.codes == "-")) {
983 ##- ## then use previous code for these (things like "20k", "300k")
984 ##- ## sequentially from the left:
985 ##- for(k in which(id)) {
986 ##- dec.codes[k] <- dec.codes[k - 1]
987 ##- ii <- 1+e10 == k
988 ##- e10[ii] <- e10[ii] - 1
989 ##- }
990 ##- }
991 paste0(round(n/ 10^(e10 + 1 - ndig)), dec.codes[1 + e10])
992 }
993
994 code2n <- function(ncod, ndig = 1, dec.codes = c("","d","c","k"))
995 {
996 ## The inverse function to n.code
997 le <- nchar(ncod)
998 cod <- substring(ncod, le, le)
999 as.integer(substring(ncod, 1, le-1)) * 10^(match(cod, dec.codes)-1)
1000 }
1001
1002 nr.sign.chg <- function(y)
1003 {
1004 ## Purpose: Compute number of sign changes in sequence
1005 ## Be careful with y[i] that were 0 !!
1006 y <- sign(c(y))
1007 y <- y[y != 0]
1008 sum(y[-1] != y[-length(y)])
1009 }
1010
1011 unif <- function(n, round.dig = 1 + trunc(log10(n)))
1012 {
1013 ## Purpose: Give regular points on [-c,c] with mean 0 and variance ~= 1
1014 if(n %% 2 == 0) {
1015 if(n > 0) round((2 * 1:n - (n + 1)) * sqrt(3/(n * (n + 1))), round.dig)
1016 } else {
1017 m <- n %/% 2 #--> m+1 = (n+1)/2
1018 ( - m:m) * round(sqrt(6/((m + 1) * n)), round.dig)
1019 }
1020 }
1021
1022 prt.DEBUG <- function(..., LEVEL = 1) {
1023 stop("prt.DEBUG() is defunct: use a 'verbose' argument or options(verbose=.) instead")
1024 ## if (exists("DEBUG", where = 1) && DEBUG >= LEVEL )#
1025 ## ##
1026 ## cat(paste0("in '", sys.call(sys.nframe()-1)[1], "':"), ..., "\n")
1027 }
1028
1029
1030
1031 ##' @title Read an Emacs Org Table by read.table()
1032 ## --> ../man/read.org.table.Rd
1033 read.org.table <- function(file, header = TRUE, skip = 0,
1034 encoding = "native", fileEncoding = "",
1035 text, quiet=FALSE, ...) {
1036 ## file - text handling --- cut'n'paste from read.table()'s header
1037 if (missing(file) && !missing(text)) {
1038 file <- textConnection(text, encoding = "UTF-8")
1039 on.exit(close(file))
1040 }
1041 if(is.character(file)) {
1042 file <- if(nzchar(fileEncoding))
1043 file(file, "rt", encoding = fileEncoding) else file(file, "rt")
1044 on.exit(close(file))
1045 }
1046 if(!inherits(file, "connection"))
1047 stop("'file' must be a character string or connection")
1048 if(!isOpen(file, "rt")) {
1049 open(file, "rt")
1050 on.exit(close(file))
1051 }
1052 if(skip > 0L) readLines(file, skip)
1053 ll <- readLines(file, encoding=encoding)
1054 close(file); on.exit()
1055 ## drop |--------+---------+--------+--| :
1056 if(length(i <- grep("---+\\+--", ll[1:3]))) ll <- ll[-i]
1057 ## drop beginning and ending "|" :
1058 ll <- sub("^ *\\|", "",
1059 sub("\\| *$", "", ll))
1060 if(header) { ## assume header in first 2 lines
1061 ii <- if(nchar(ll[1]) < 2) 2 else 1
1062 ## header line
1063 hl <- ll[ii]
1064 ## drop header line(s)
1065 ll <- ll[-seq_len(ii)]
1066 ## split the header lines into column names
1067 col.names <- sub("^ +", "", sub(" +$", "", strsplit(hl, " *\\| *") [[1L]]))
1068 }
1069 ## drop empty lines at end only
1070 while(grepl("^ *$", tail(ll, 1L))) ll <- ll[-length(ll)]
1071 nent <- count.fields(textConnection(ll), sep="|")
1072 ok <- nent == (p <- length(col.names))
1073 nrows <- if(all(ok)) length(ok)
1074 else match(FALSE, ok) - 1L # 1..n, where n+1 contains the first non-match
1075 if("nrows" %in% ...names())
1076 nrows <- min(nrows, list(...)$nrows)
1077 else if(!quiet && nrows < 0.95*length(nent))
1078 message(
1079 sprintf("Will read the first %d rows (of each %d columns) of %d (non-empty non-header) lines",
1080 nrows, p, length(nent)))
1081 f.ll <- textConnection(ll)# , encoding = "UTF-8" is *NOT* good
1082 on.exit(close(f.ll))
1083 read.table(f.ll, header=FALSE, sep = "|",
1084 col.names = col.names, nrows=nrows, ...) # , encoding = "UTF-8" *not* good
1085 }
1086
1087 ## as compact numeric format() as possible
1088 formatN <- function(x, digits = 1L, sci = c(-1L,-2L)) {
1089 stopifnot(is.numeric(x) || is.complex(x), sci == as.integer(sci))
1090 if(length(sci) == 1L) sci <- c(sci,sci)
1091 sub("e-0*", "e-",
1092 sub("e\\+0*","e",
1093 vapply(x, function(u) format(u, digits=digits, scientific = sci[if(abs(u) < 1) 1 else 2]), "")))
1094 }
1095
1096 ## called this 'show01()` first --- useful to show long bit-strings / -vectors
1097 ##' @example z <- rbinom(120, size = 1, prob = 1/2); compact01(z) compact01(z, 40) ...
1098 compact01 <- function(z, ncol = 50L) {
1099 stopifnot(ncol == (nc <- as.integer(ncol)), nc >= 1L)
1100 if((lz <- length(z)) == 0L)
1101 return(matrix(character(), 0L, 1L))
1102 sn <- symnum(z == 1)# sn[]: character & 'noquote'
1103 if (nc > lz)
1104 nc <- lz
1105 else if((r <- lz %% nc) != 0) # fill "remainder" with blanks
1106 sn[lz + seq_len(nc - r)] <- " "
1107 ss <- matrix(sn, ncol=nc, byrow=TRUE)
1108 ## return character matrix {K x 1} each row a string of length `nc`,
1109 ## with empty colname and 'bit counting' rownames):
1110 ## if R >= 4.1.0 apply(ss, 1L, paste, collapse="") |> cbind(deparse.level = 0L) |> noquote(),
1111 `dimnames<-`(noquote(cbind(apply(ss, 1L, paste, collapse=""), deparse.level = 0L)),
1112 list(format(1 + nc*(0:(nrow(ss)-1L))), ""))
1113 }