File: utils.R

package info (click to toggle)
r-cran-sessioninfo 1.2.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 536 kB
  • sloc: sh: 14; makefile: 2
file content (48 lines) | stat: -rw-r--r-- 866 bytes parent folder | download | duplicates (3)
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

`%||%` <- function(l, r) if (is.null(l)) r else l

sort_ci <- function(x) {
  old <- Sys.getlocale("LC_COLLATE")
  on.exit(Sys.setlocale("LC_COLLATE", old), add = TRUE)
  Sys.setlocale("LC_COLLATE", "C")
  x[order(tolower(x), x)]
}

is_string <- function(x) {
  is.character(x) && length(x) == 1 && !is.na(x)
}

is_flag <- function(x) {
  is.logical(x) && length(x) == 1 && !is.na(x)
}

order_by_name <- function(x) {
  if (!length(x)) {
    x
  } else if (is.null(names(x))) {
    stop("Cannot order by name, no names")
  } else {
    x[order(names(x))]
  }
}

drop_null <- function(x) {
  x[! vapply(x, is.null, logical(1))]
}

last <- function(x) {
  x[length(x)]
}

empty <- function(x) {
  grepl("^\\s*$", x)
}

str_trim <- function(x, width) {
  stopifnot(width >= 2)
  if (nchar(x) <= width) {
    x
  } else {
    paste0(substr(x, 1, width - 1), "~")
  }
}