Debian Codegraph @

R/utils-sfmisc.R

raw
1 # sfmisc utils 1.0.0.9034
2
3
4
5
6 # utils -------------------------------------------------------------------
7
8 # nocov start
9 # commonly used utility functions included from the package sfmisc
10
11
12 #' Paste and Truncate
13 #'
14 #' @param x a vector
15 #' @param width (maximum) width of result
16 #' @param dots `character` scalar. String to use for ellipses
17 #' @inheritParams paste
18 #'
19 #' @return a `character` scalar
20 #' @noRd
21 #'
22 #' @examples
23 #' ptrunc(month.abb)
24 #' ptrunc(month.abb, month.name)
25 #'
26 ptrunc <- function(
27 ...,
28 width = 40L,
29 sep = ", ",
30 collapse = ", ",
31 dots = " ..."
32 ){
33 assert(width > 7L, "The minimum supported width is 8")
34 x <- paste(..., sep = sep, collapse = collapse)
35
36 sel <- vapply(x, nchar, integer(1), USE.NAMES = FALSE) > width
37
38 x[sel] <- strtrim(x[sel], width = width - 4L)
39 x[sel] <- paste0(gsub(",{0,1}\\s*$", "", x[sel]), dots)
40 x
41 }
42
43
44
45
46 fmt_class <- function(x, open = "<", close = ">"){
47 paste0(open, paste(x, collapse = "/"), close)
48 }
49
50
51
52
53 #' @param x any \R object
54 #' @param ignore subclasses to ignore
55 #' @noRd
56 class_fmt <- function(x, ignore = NULL){
57 fmt_class(setdiff(class(x), ignore))
58 }
59
60
61 compact <- function(x){
62 x[!vapply(x, is_empty, FALSE)]
63 }
64
65
66 replace_empty <- function(x, fallback = "<NULL>"){
67 for (i in seq_along(x)){
68 if (is_empty(x[[i]])){
69 x[[i]] <- fallback
70 }
71 }
72 x
73 }
74
75
76 walk <- function(.x, .f, ...){
77 for (i in seq_along(.x)){
78 .f(.x[[i]], ...)
79 }
80
81 invisible(.x)
82 }
83
84
85
86
87 # assertions --------------------------------------------------------------
88
89 #' Assert a condition
90 #'
91 #' A simpler and more efficient for [base::stopifnot()] that has an easy
92 #' mechanism for supplying custom error messages. As opposed to `stopifnot()`,
93 #' `assert()` only works with a single (scalar) assertions.
94 #'
95 #' @param cond `TRUE` or `FALSE` (without any attributes). `FALSE` will throw
96 #' an exception with an automatically constructed error message (if `...`
97 #' was not supplied). Anything else will throw an exception stating that
98 #' `cond` was not valid.
99 #' @param ... passed on to [stop()]
100 #' @param call. passed on to [stop()]
101 #' @param domain passed on to [stop()]
102 #'
103 #' @noRd
104 #'
105 #' @return TRUE on success
106 #'
107 #' @examples
108 #'
109 #' \dontrun{
110 #' assert(1 == 1)
111 #' assert(1 == 2)
112 #' }
113 #'
114 #'
115 assert <- function(
116 cond,
117 ...,
118 call. = FALSE,
119 domain = NULL
120 ){
121 if (isTRUE(cond)){
122 return(TRUE)
123 } else if (isFALSE(cond)){
124 if (identical(length(list(...)), 0L)){
125 msg <- paste0("`", deparse(match.call()[[2]]), "`", " is not 'TRUE'")
126 stop(msg, call. = call., domain = domain)
127 } else {
128 suppressWarnings( stop(..., call. = call., domain = domain) )
129 }
130
131 } else {
132 stop("Assertion must be either 'TRUE' or 'FALSE'")
133 }
134 }
135
136
137
138
139 assert_namespace <- function(...){
140 pkgs <- c(...)
141
142 res <- vapply(pkgs, requireNamespace, logical(1), quietly = TRUE)
143 if (all(res)){
144 return(invisible(TRUE))
145
146 } else {
147 miss <- pkgs[!res]
148
149 if (identical(length(miss), 1L)){
150 msg <- sprintf(paste(
151 "This function requires the package '%s'. You can install it with",
152 '`install.packages("%s")`.'), miss, miss
153 )
154 } else {
155 msg <- sprintf(
156 paste(
157 "This function requires the packages %s. You can install them with",
158 "`install.packages(%s)`."
159 ),
160 paste(miss, collapse = ", "),
161 paste0("c(", paste(paste0('\"', miss, '\"'), collapse = ", "), ")")
162 )
163 }
164 }
165
166 stop(msg, call. = FALSE)
167 }
168
169
170
171
172 # predicates --------------------------------------------------------------
173
174
175
176 is_error <- function(x){
177 inherits(x, "error")
178 }
179
180
181
182
183 is_try_error <- function(x){
184 inherits(x, "try-error")
185 }
186
187
188
189
190 is_scalar <- function(x){
191 identical(length(x), 1L)
192 }
193
194
195
196
197 is_POSIXct <- function(x){
198 inherits(x, "POSIXct")
199 }
200
201
202
203
204 is_scalar_POSIXct <- function(x){
205 is_POSIXct(x) && is_scalar(x)
206 }
207
208
209
210
211 is_POSIXlt <- function(x){
212 inherits(x, "POSIXlt")
213 }
214
215
216
217
218 is_scalar_POSIXlt <- function(x){
219 is_POSIXlt(x) && is_scalar(x)
220 }
221
222
223
224
225 is_POSIXt <- function(x){
226 inherits(x, "POSIXt")
227 }
228
229
230
231
232 is_scalar_POSIXt <- function(x){
233 is_POSIXt(x) && is_scalar(x)
234 }
235
236
237
238
239 is_Date <- function(x){
240 inherits(x, "Date")
241 }
242
243
244
245
246 is_scalar_Date <- function(x){
247 is_Date(x) && is_scalar(x)
248 }
249
250
251
252
253 is_scalar_list <- function(x){
254 is_list(x) && is_scalar(x)
255 }
256
257
258
259
260 is_scalar_atomic <- function(x){
261 is.atomic(x) && is_scalar(x)
262 }
263
264
265
266
267 is_scalar_logical <- function(x){
268 is.logical(x) && is_scalar(x)
269 }
270
271
272
273
274 is_scalar_integer <- function(x){
275 is.integer(x) && is_scalar(x)
276 }
277
278
279
280
281 is_scalar_factor <- function(x){
282 is.factor(x) && is_scalar(x)
283 }
284
285
286
287
288 is_scalar_list <- function(x){
289 is.list(x) && is_scalar(x)
290 }
291
292
293
294
295 is_scalar_numeric <- function(x){
296 is.numeric(x) && is_scalar(x)
297 }
298
299
300
301
302 is_scalar_character <- function(x){
303 is.character(x) && is_scalar(x)
304 }
305
306
307
308
309 is_vector <- function(x){
310 is.atomic(x) || is.list(x)
311 }
312
313
314
315
316 is_bool <- function(x){
317 is.logical(x) && !anyNA(x)
318 }
319
320
321
322
323 #' Check if Object is a Boolean
324 #'
325 #' Check wheter an object is either `TRUE` or `FALSE`.
326 #'
327 #' @param x Any \R Object.
328 #' @return either `TRUE` or `FALSE`
329 #' @noRd
330 #'
331 is_scalar_bool <- function(x){
332 is.logical(x) && length(x) == 1L && !is.na(x)
333 }
334
335
336
337
338 #' Check if Object is Integer-like
339 #'
340 #' Check wheter an object is either `TRUE` or `FALSE`.
341 #'
342 #' @param x Any \R Object.
343 #' @return either `TRUE` or `FALSE`
344 #' @noRd
345 #'
346 is_integerish <- function(x){
347 if (!is.numeric(x)){
348 FALSE
349 } else {
350 all(as.integer(x) == x)
351 }
352 }
353
354
355
356
357 is_scalar_integerish <- function(x){
358 is_scalar(x) && is_integerish(x)
359 }
360
361
362
363
364 is_n <- function(x){
365 is_scalar_integerish(x) && isTRUE(x > 0)
366 }
367
368
369
370
371 is_n0 <- function(x){
372 is_scalar_integerish(x) && isTRUE(x >= 0)
373 }
374
375
376
377
378 #' Check if Objects have the same length
379 #'
380 #' @param ... Any number of \R Objects.
381 #'
382 #' @return either `TRUE` or `FALSE`
383 #' @noRd
384 is_equal_length <- function(...){
385 lengths <- vapply(list(...), length, 1L)
386 identical(length(unique(lengths)), 1L)
387 }
388
389
390
391
392 #' Check if Object has length 0
393 #'
394 #' Check whether an object is either `TRUE` or `FALSE`.
395 #'
396 #' @param x Any \R Object.
397 #' @return either `TRUE` or `FALSE`
398 #' @noRd
399 #'
400 is_empty <- function(x){
401 !length(x)
402 }
403
404
405
406
407 #' Check if a String is Blank
408 #'
409 #' Check wheter a character vector contains only of spaces
410 #'
411 #' @param x Any \R Object.
412 #' @return either `TRUE` or `FALSE`
413 #' @noRd
414 #'
415 is_blank <- function(x){
416 trimws(x) == ""
417 }
418
419
420
421
422 #' Test if a Vector or Combination of Vectors is a Candidate Key
423 #'
424 #' Checks if all elements of the atomic vector `x`, or the combination of
425 #' all elements of `x` if `x` is a `list`, are unique and neither `NA` or
426 #' `infinite`.
427 #'
428 #' @param x a atomic vector or a list of atomic vectors
429 #'
430 #' @return `TRUE/FALSE`
431 #' @noRd
432 #'
433 #' @examples
434 #'
435 #' is_candidate_key(c(1, 2, 3))
436 #' is_candidate_key(c(1, 2, NA))
437 #' is_candidate_key(c(1, 2, Inf))
438 #'
439 #' td <- data.frame(
440 #' x = 1:10,
441 #' y = 1:2,
442 #' z = 1:5
443 #' )
444 #'
445 #' is_candidate_key(list(td$x, td$z))
446 #' # a data.frame is just a special list
447 #' is_candidate_key(td[, c("y", "z")])
448 is_candidate_key <- function(x){
449
450 if (is.atomic(x)){
451 # !is.infinite instead of is.finite because x can be a character vector
452 length(x) > 1 &&
453 all(!is.infinite(x)) &&
454 !anyNA(x) &&
455 identical(length(unique(x)), length(x))
456 } else if (is.list(x)){
457 length(x) > 0 &&
458 length(x[[1]] > 0) &&
459 do.call(is_equal_length, x) &&
460 all(vapply(x, function(.x) all(!is.infinite(.x)), logical(1))) &&
461 all(vapply(x, function(.x) !anyNA(.x), logical(1))) &&
462 !anyDuplicated(as.data.frame(x)) > 0
463 }
464 }
465
466
467
468
469 # https://modern-sql.com/feature/is-distinct-from
470 is_not_distinct_from <- function(x, y){
471 ((x == y) & !is.na(x) & !is.na(y)) | (is.na(x) & is.na(y))
472 }
473
474
475
476
477 is_distinct_from <- function(x, y){
478 ((x != y) & !is.na(x) & !is.na(y)) | (is.na(x) != is.na(y))
479 }
480
481
482
483
484 is_windows_path <- function(x){
485 nchar(x) >= 2 & grepl("^[A-Za-z].*", x) & substr(x, 2, 2) == ":"
486 }
487
488
489
490 # equalish ----------------------------------------------------------------
491
492 #' Check for equality within a tolerance level
493 #'
494 #'
495 #'
496 #' @param x,y `numeric` vectors
497 #' @param tolerance `numeric` scalar. tolerance level (absolute value). Defaults
498 #' to `.Machine$double.eps^0.5` which is a sensible default for comparing
499 #' floating point numbers.
500 #'
501 #' @return `equalish()` returns TRUE if the absolute difference between `x` and
502 #' `y` is less than `tolerance`.
503 #' @noRd
504 #' @seealso [.Machine]
505 #'
506 #'
507 #' @examples
508 #' a <- 0.7
509 #' b <- 0.2
510 #' a - b == 0.5
511 #' equalish(a - b, 0.5)
512 #'
513 equalish <- function(x, y, tolerance = .Machine$double.eps ^ 0.5){
514 assert(is_scalar_numeric(tolerance) && tolerance >= 0)
515 abs(x - y) < tolerance
516 }
517
518
519
520
521 #' @return `equalish_frac()` returns `TRUE` if the relative difference between
522 #' `x` and `y` is smaller than `tolerance`. The relative difference is
523 #' defined as `abs(x - y) / pmax(abs(x), abs(y))`. If both `x` and `y` are
524 #' `0` the relative difference is not defined, but this function will still
525 #' return `TRUE`.
526 #'
527 #' @noRd
528 #' @examples
529 #'
530 #' equalish_frac(1000, 1010, tolerance = 0.01)
531 #' equalish_frac(1000, 1010, tolerance = 0.009)
532 #' equalish_frac(0, 0)
533 #'
534 equalish_frac <- function(x, y, tolerance = .Machine$double.eps ^ 0.5){
535 assert(is_scalar_numeric(tolerance) && tolerance >= 0)
536 res <- abs(x - y) / pmax(abs(x), abs(y)) < tolerance
537 res[x == 0 & y == 0] <- TRUE
538 res
539 }
540
541
542
543
544 # all_are -----------------------------------------------------------------
545
546 #' Convert vector if identical elements to scalar
547 #'
548 #' Returns `unique(x)` if all elements of `x` are identical, throws an error if
549 #' not.
550 #'
551 #' @inheritParams all_are_identical
552 #'
553 #' @return A scalar of the same type as `x`
554 #' @noRd
555 as_scalar <- function(x){
556 res <- unique(x)
557 if (is_scalar(res)){
558 return(res)
559 } else {
560 stop("Not all elements of x are identical")
561 }
562 }
563
564
565
566
567 #' Test if all elements of a vector are identical
568 #'
569 #' @param x any object that can be handled by [unique()] (usually a vector or
570 #' list)
571 #' @param empty_value Value to return if function is called on a vector of
572 #' length 0 (e.g. `NULL`, `numeric()`, ...)
573 #'
574 #' @noRd
575 #' @family special equality checks
576 #' @return `TRUE/FALSE`
577 #'
578 #' @examples
579 #'
580 #' all_are_identical(c(1,2,3))
581 #' all_are_identical(c(1,1,1))
582 #'
583 all_are_identical <- function(x, empty_value = FALSE) {
584 assert(length(empty_value) <= 1)
585
586 if (length(x) > 0L) {
587 return(identical(length(unique(x)), 1L))
588
589 } else {
590
591 if (is.null(x)){
592 warning("'x' is NULL")
593 } else {
594 warning("'x' is an empty vector")
595 }
596
597 return(empty_value)
598 }
599 }
600
601
602
603
604 #' Test if all elements of a vector are unique
605 #'
606 #' @inheritParams all_are_identical
607 #'
608 #' @return TRUE/FALSE
609 #'
610 #' @noRd
611 #' @family special equality checks
612 #'
613 #' @examples
614 #'
615 #' all_are_identical(c(1,2,3))
616 #' all_are_identical(c(1,1,1))
617 #'
618 all_are_distinct <- function(
619 x,
620 empty_value = FALSE
621 ){
622 assert(length(empty_value) <= 1)
623
624 if (identical(length(x), 1L)) {
625 return(TRUE)
626
627 } else if (length(x) > 1L) {
628 return(identical(length(unique(x)), length(x)))
629
630 } else {
631
632 if (is.null(x)){
633 warning("'x' is NULL")
634 } else {
635 warning("'x' is an empty vector")
636 }
637
638 return(empty_value)
639 }
640 }
641
642
643
644
645 n_distinct <- function(x){
646 length(unique(x))
647 }
648
649
650
651
652 # misc --------------------------------------------------------------------
653
654
655 pad_left <- function(
656 x,
657 width = max(nchar(paste(x))),
658 pad = " "
659 ){
660 diff <- pmax(width - nchar(paste(x)), 0L)
661 padding <-
662 vapply(diff, function(i) paste(rep.int(pad, i), collapse = ""), character(1))
663 paste0(padding, x)
664 }
665
666
667
668
669 pad_right <- function(
670 x,
671 width = max(nchar(paste(x))),
672 pad = " "
673 ){
674 diff <- pmax(width - nchar(paste(x)), 0L)
675 padding <-
676 vapply(diff, function(i) paste(rep.int(pad, i), collapse = ""), character(1))
677 paste0(x, padding)
678 }
679
680
681
682
683 `%||%` <- function(x, y){
684 if (is.null(x))
685 y
686 else (x)
687 }
688
689
690
691
692 preview_object <- function(
693 x,
694 width = 32,
695 brackets = c("(", ")"),
696 quotes = c("`", "`"),
697 dots = ".."
698 ){
699 if (is.function(x)){
700 fmls <- names(formals(x))
701 len_fmls <- length(fmls)
702
703 if (len_fmls > 4){
704 fmls <- fmls[1:4]
705 fmls_fmt <- paste(fmls, collapse = ", ")
706 fmls_fmt <- paste0(fmls_fmt, ", +", len_fmls - length(fmls), "")
707 } else {
708 fmls_fmt <- paste(fmls, collapse = ", ")
709 }
710 return(fmt_class(paste(
711 fmt_class(class(x), open = "", close = ""), "(", fmls_fmt, ")",
712 sep = ""
713 )))
714 }
715
716
717 if (!is.atomic(x))
718 return(class_fmt(x))
719
720 if (is.numeric(x))
721 x <- format(x, justify = "none", drop0trailing = TRUE, trim = TRUE)
722
723 res <- ptrunc(x, collapse = ", ", width = width, dots = dots)
724
725 if (length(x) > 1)
726 res <- paste0(brackets[[1]], res, brackets[[2]])
727 else
728 res <- paste0(quotes[[1]], res, quotes[[2]])
729
730 res
731 }
732
733
734
735
736 #' Collapse text vectors with a comma
737 #'
738 #' @param x `character` vector
739 #'
740 #' @return a `character` scalar
741 #' @noRd
742 comma <- function(..., collapse = ", "){
743 paste(unlist(c(...)), collapse = collapse)
744 }
745
746
747
748
749 #' Collapse text vectors with a comma (no duplicates)
750 #'
751 #' @param x `character` vector
752 #'
753 #' @return a `character` scalar
754 #' @noRd
755 commaset <- function(..., collapse = ", "){
756 paste(sort(unique(unlist(c(...)))), collapse = collapse)
757 }
758
759
760
761
762 #' Clean up paths to make them comparable, inspired by fs::path_tidy
763 #'
764 #' @param x `character` vector
765 #'
766 #' @return a `character` vector
767 #' @noRd
768 path_tidy <- function(x){
769 x <- gsub("\\\\", "/", x)
770 x <- gsub("(?!^)/+", "/", x, perl = TRUE)
771
772 sel <- x != "/"
773 x[sel] <- gsub("/$", "", x[sel])
774
775 sel <- is_windows_path(x)
776
777 if (any(sel)){
778 clean_win <- function(.x){
779 substr(.x, 1, 1) <- toupper(substr(.x, 1 ,1))
780 .sel <- nchar(.x) == 2
781 .x[.sel] <- paste0(.x[.sel], "/")
782 .x
783 }
784
785 x[sel] <- clean_win(x[sel])
786 }
787
788 x
789 }
790
791
792
793
794 #' Return (unique) duplicated elements of a vector or rows of a data.frame
795 #'
796 #' For every element/row of `x` that has at least one duplicate, return one
797 #' instance of that element.
798 #'
799 #' @param x an [atomic] vector or [data.frame]
800 #' @param ... passed on to [duplicated()]
801 #'
802 #' @noRd
803 #'
804 #' @examples
805 #' dupes(c(1, 1, 1, 2))
806 #' dupes(cars[c(1, 1, 1, 2), ])
807 dupes <- function(x, ...){
808
809 if (is.atomic(x)){
810 sort(unique(x[duplicated(x, ...)]))
811 } else if (is.data.frame(x)){
812 res <- unique(x[duplicated(x, ...), ])
813 row.names(res) <- NULL
814 res
815 }
816 }
817
818 # nocov end