| 1 |
`%|%` = function(x, y) if (length(x)) x else y |
| 2 |
if (getRversion() < '4.4.0') `%||%` = function(x, y) if (is.null(x)) y else x |
| 3 |
|
| 4 |
stop2 = function(...) stop(..., call. = FALSE) |
| 5 |
|
| 6 |
warning2 = function(...) warning(..., call. = FALSE) |
| 7 |
|
| 8 |
#' Obtain an attribute of an object without partial matching |
| 9 |
#' |
| 10 |
#' An abbreviation of [`base::attr`]`(exact = TRUE)`. |
| 11 |
#' @param ... Passed to [base::attr()] (without the `exact` argument). |
| 12 |
#' @export |
| 13 |
#' @examples |
| 14 |
#' z = structure(list(a = 1), foo = 2) |
| 15 |
#' base::attr(z, 'f') # 2 |
| 16 |
#' xfun::attr2(z, 'f') # NULL |
| 17 |
#' xfun::attr2(z, 'foo') # 2 |
| 18 |
attr2 = function(...) base::attr(..., exact = TRUE) |
| 19 |
|
| 20 |
#' Set environment variables |
| 21 |
#' |
| 22 |
#' Set environment variables from a named character vector, and return the old |
| 23 |
#' values of the variables, so they could be restored later. |
| 24 |
#' |
| 25 |
#' The motivation of this function is that [Sys.setenv()] does not |
| 26 |
#' return the old values of the environment variables, so it is not |
| 27 |
#' straightforward to restore the variables later. |
| 28 |
#' @param vars A named character vector of the form `c(VARIABLE = VALUE)`. |
| 29 |
#' If any value is `NA`, this function will try to unset the variable. |
| 30 |
#' @return Old values of the variables (if not set, `NA`). |
| 31 |
#' @export |
| 32 |
#' @examples |
| 33 |
#' vars = xfun::set_envvar(c(FOO = '1234')) |
| 34 |
#' Sys.getenv('FOO') |
| 35 |
#' xfun::set_envvar(vars) |
| 36 |
#' Sys.getenv('FOO') |
| 37 |
set_envvar = function(vars) { |
| 38 |
if (is.null(nms <- names(vars)) || any(nms == '')) stop( |
| 39 |
"The 'vars' argument must take a named character vector." |
| 40 |
) |
| 41 |
vals = Sys.getenv(nms, NA, names = TRUE) |
| 42 |
i = is.na(vars) |
| 43 |
suppressWarnings(Sys.unsetenv(nms[i])) |
| 44 |
if (length(vars <- vars[!i])) do.call(Sys.setenv, as.list(vars)) |
| 45 |
invisible(vals) |
| 46 |
} |
| 47 |
|
| 48 |
#' Retrieve a global option from both `options()` and environment variables |
| 49 |
#' |
| 50 |
#' If the option exists in [options()], use its value. If not, query the |
| 51 |
#' environment variable with the name `R_NAME` where `NAME` is the capitalized |
| 52 |
#' option name with dots substituted by underscores. For example, for an option |
| 53 |
#' `xfun.foo`, first we try `getOption('xfun.foo')`; if it does not exist, we |
| 54 |
#' check the environment variable `R_XFUN_FOO`. |
| 55 |
#' |
| 56 |
#' This provides two possible ways, whichever is more convenient, for users to |
| 57 |
#' set an option. For example, global options can be set in the [.Rprofile] |
| 58 |
#' file, and environment variables can be set in the [.Renviron] file. |
| 59 |
#' @param name The option name. |
| 60 |
#' @param default The default value if the option is not found in [options()] or |
| 61 |
#' environment variables. |
| 62 |
#' @return The option value. |
| 63 |
#' @export |
| 64 |
#' @examples |
| 65 |
#' xfun::env_option('xfun.test.option') # NULL |
| 66 |
#' |
| 67 |
#' Sys.setenv(R_XFUN_TEST_OPTION = '1234') |
| 68 |
#' xfun::env_option('xfun.test.option') # 1234 |
| 69 |
#' |
| 70 |
#' options(xfun.test.option = TRUE) |
| 71 |
#' xfun::env_option('xfun.test.option') # TRUE (from options()) |
| 72 |
#' options(xfun.test.option = NULL) # reset the option |
| 73 |
#' xfun::env_option('xfun.test.option') # 1234 (from env var) |
| 74 |
#' |
| 75 |
#' Sys.unsetenv('R_XFUN_TEST_OPTION') |
| 76 |
#' xfun::env_option('xfun.test.option') # NULL again |
| 77 |
#' |
| 78 |
#' xfun::env_option('xfun.test.option', FALSE) # use default |
| 79 |
env_option = function(name, default = NULL) { |
| 80 |
if (name %in% names(.Options)) return(.Options[[name]]) |
| 81 |
name = toupper(paste0('R_', gsub('[.]', '_', name))) |
| 82 |
envs = Sys.getenv() |
| 83 |
if (name %in% names(envs)) envs[[name]] else default |
| 84 |
} |
| 85 |
|
| 86 |
#' Call `on.exit()` in a parent function |
| 87 |
#' |
| 88 |
#' The function [on.exit()] is often used to perform tasks when the |
| 89 |
#' current function exits. This `exit_call()` function allows calling a |
| 90 |
#' function when a parent function exits (thinking of it as inserting an |
| 91 |
#' `on.exit()` call into the parent function). |
| 92 |
#' @param fun A function to be called when the parent function exits. |
| 93 |
#' @param n The parent frame number. For `n = 1`, `exit_call(fun)` is |
| 94 |
#' the same as `on.exit(fun())`; `n = 2` means adding |
| 95 |
#' `on.exit(fun())` in the parent function; `n = 3` means the |
| 96 |
#' grandparent, etc. |
| 97 |
#' @param ... Other arguments to be passed to `on.exit()`. |
| 98 |
#' @references This function was inspired by Kevin Ushey: |
| 99 |
#' <https://yihui.org/en/2017/12/on-exit-parent/> |
| 100 |
#' @export |
| 101 |
#' @examples |
| 102 |
#' f = function(x) { |
| 103 |
#' print(x) |
| 104 |
#' xfun::exit_call(function() print('The parent function is exiting!')) |
| 105 |
#' } |
| 106 |
#' g = function(y) { |
| 107 |
#' f(y) |
| 108 |
#' print('f() has been called!') |
| 109 |
#' } |
| 110 |
#' g('An argument of g()!') |
| 111 |
exit_call = function(fun, n = 2, ...) { |
| 112 |
do.call( |
| 113 |
on.exit, list(substitute(fun(), list(fun = fun)), add = TRUE, ...), |
| 114 |
envir = parent.frame(n) |
| 115 |
) |
| 116 |
} |
| 117 |
|
| 118 |
#' Evaluate an expression under a specified working directory |
| 119 |
#' |
| 120 |
#' Change the working directory, evaluate the expression, and restore the |
| 121 |
#' working directory. |
| 122 |
#' @param dir Path to a directory. |
| 123 |
#' @param expr An R expression. |
| 124 |
#' @export |
| 125 |
#' @examples |
| 126 |
#' library(xfun) |
| 127 |
#' in_dir(tempdir(), {print(getwd()); list.files()}) |
| 128 |
in_dir = function(dir, expr) { |
| 129 |
owd = setwd(dir); on.exit(setwd(owd)) |
| 130 |
expr |
| 131 |
} |
| 132 |
|
| 133 |
#' Parse R code and do not keep the source |
| 134 |
#' |
| 135 |
#' An abbreviation of `parse(keep.source = FALSE)`. |
| 136 |
#' @param code A character vector of the R source code. |
| 137 |
#' @export |
| 138 |
#' @return R [expression()]s. |
| 139 |
#' @examples library(xfun) |
| 140 |
#' parse_only('1+1'); parse_only(c('y~x', '1:5 # a comment')) |
| 141 |
#' parse_only(character(0)) |
| 142 |
parse_only = function(code) { |
| 143 |
if (length(code) == 0) return(expression()) |
| 144 |
parse(text = code, keep.source = FALSE) |
| 145 |
} |
| 146 |
|
| 147 |
#' Try to evaluate an expression silently |
| 148 |
#' |
| 149 |
#' An abbreviation of `try(silent = TRUE)`. |
| 150 |
#' @param expr An R expression. |
| 151 |
#' @export |
| 152 |
#' @examples library(xfun) |
| 153 |
#' z = try_silent(stop('Wrong!')) |
| 154 |
#' inherits(z, 'try-error') |
| 155 |
try_silent = function(expr) try(expr, silent = TRUE) |
| 156 |
|
| 157 |
#' Try an expression and see if it throws an error |
| 158 |
#' |
| 159 |
#' Use [tryCatch()] to check if an expression throws an error. |
| 160 |
#' @inheritParams try_silent |
| 161 |
#' @return `TRUE` (error) or `FALSE` (success). |
| 162 |
#' @export |
| 163 |
#' @examples |
| 164 |
#' xfun::try_error(stop('foo')) # TRUE |
| 165 |
#' xfun::try_error(1:10) # FALSE |
| 166 |
try_error = function(expr) { |
| 167 |
err = FALSE |
| 168 |
tryCatch(expr, error = function(e) err <<- TRUE) |
| 169 |
err |
| 170 |
} |
| 171 |
|
| 172 |
#' Retry calling a function for a number of times |
| 173 |
#' |
| 174 |
#' If the function returns an error, retry it for the specified number of |
| 175 |
#' times, with a pause between attempts. |
| 176 |
#' |
| 177 |
#' One application of this function is to download a web resource. Since the |
| 178 |
#' download might fail sometimes, you may want to retry it for a few more times. |
| 179 |
#' @param fun A function. |
| 180 |
#' @param ... Arguments to be passed to the function. |
| 181 |
#' @param .times The number of times. |
| 182 |
#' @param .pause The number of seconds to wait before the next attempt. |
| 183 |
#' @export |
| 184 |
#' @examplesIf interactive() |
| 185 |
#' # read the GitHub releases info of the repo yihui/xfun |
| 186 |
#' xfun::retry(xfun::github_releases, 'yihui/xfun') |
| 187 |
retry = function(fun, ..., .times = 3, .pause = 5) { |
| 188 |
for (i in seq_len(.times)) { |
| 189 |
if (!inherits(res <- tryCatch(fun(...), error = identity), 'error')) |
| 190 |
return(res) |
| 191 |
Sys.sleep(.pause) |
| 192 |
} |
| 193 |
stop(res$message, call. = FALSE) |
| 194 |
} |
| 195 |
|
| 196 |
gsubi = function(...) gsub(..., ignore.case = TRUE) |
| 197 |
gsubf = function(...) gsub(..., fixed = TRUE) |
| 198 |
|
| 199 |
#' Turn the output of [str()] into a tree diagram |
| 200 |
#' |
| 201 |
#' The super useful function `str()` uses \verb{..} to indicate the level |
| 202 |
#' of sub-elements of an object, which may be difficult to read. This function |
| 203 |
#' uses vertical pipes to connect all sub-elements on the same level, so it is |
| 204 |
#' clearer which elements belong to the same parent element in an object with a |
| 205 |
#' nested structure (such as a nested list). |
| 206 |
#' @param ... Arguments to be passed to [str()] (note that the |
| 207 |
#' `comp.str` is hardcoded inside this function, and it is the only |
| 208 |
#' argument that you cannot customize). |
| 209 |
#' @return A character string as a [raw_string()]. |
| 210 |
#' @export |
| 211 |
#' @examples fit = lsfit(1:9, 1:9) |
| 212 |
#' str(fit) |
| 213 |
#' xfun::tree(fit) |
| 214 |
#' |
| 215 |
#' fit = lm(dist ~ speed, data = cars) |
| 216 |
#' str(fit) |
| 217 |
#' xfun::tree(fit) |
| 218 |
#' |
| 219 |
#' # some trivial examples |
| 220 |
#' xfun::tree(1:10) |
| 221 |
#' xfun::tree(iris) |
| 222 |
tree = function(...) { |
| 223 |
x = capture.output(str(..., comp.str = '$ ')) |
| 224 |
r = '^([^$-]+[$-] )(.*)$' |
| 225 |
x1 = gsub(r, '\\1', x) |
| 226 |
x2 = gsub(r, '\\2', x) |
| 227 |
x1 = gsub('[.][.]', ' ', x1) |
| 228 |
x1 = gsub('[$] $', '|-', x1) |
| 229 |
x1 = connect_pipes(x1) |
| 230 |
x3 = paste(x1, x2, sep = '') |
| 231 |
i = !grepl(r, x) |
| 232 |
x3[i] = x[i] |
| 233 |
raw_string(x3) |
| 234 |
} |
| 235 |
|
| 236 |
# for a tree diagram, connect the pipes on the same level, e.g., change |
| 237 |
|
| 238 |
# |- .. |
| 239 |
# |- .. |
| 240 |
# |
| 241 |
# |- .. |
| 242 |
|
| 243 |
# to |
| 244 |
|
| 245 |
# |- .. |
| 246 |
# |- .. |
| 247 |
# | |
| 248 |
# |- .. |
| 249 |
|
| 250 |
# this task is not complicated, but just boring nested for-loops |
| 251 |
connect_pipes = function(x) { |
| 252 |
ns = nchar(x); n = max(ns); m = length(x) |
| 253 |
if (n < 2 || m < 3) return(x) |
| 254 |
A = matrix('', nrow = m, ncol = n) |
| 255 |
x = strsplit(x, '') |
| 256 |
for (i in seq_len(m)) { |
| 257 |
A[i, seq_len(ns[i])] = x[[i]] |
| 258 |
} |
| 259 |
k = NULL |
| 260 |
for (j in seq_len(n - 1)) { |
| 261 |
for (i in seq_len(m - 2)) { |
| 262 |
if (!all(A[i, j + 0:1] == c('|', '-'))) next |
| 263 |
for (l in (i + 1):m) { |
| 264 |
cells = A[l, j + 0:1] |
| 265 |
if (all(cells == ' ')) { |
| 266 |
if (l == m) { |
| 267 |
k = NULL; break |
| 268 |
} else k = c(k, l) |
| 269 |
} else if (all(cells == c('|', '-'))) { |
| 270 |
break |
| 271 |
} else { |
| 272 |
k = NULL; break |
| 273 |
} |
| 274 |
} |
| 275 |
if (length(k) > 0) A[k, j] = '|' |
| 276 |
k = NULL |
| 277 |
} |
| 278 |
} |
| 279 |
apply(A, 1, paste, collapse = '') |
| 280 |
} |
| 281 |
|
| 282 |
pkg_file = function(...) system.file(..., package = 'xfun', mustWork = TRUE) |
| 283 |
|
| 284 |
#' Format numbers of bytes using a specified unit |
| 285 |
#' |
| 286 |
#' Call the S3 method `format.object_size()` to format numbers of bytes. |
| 287 |
#' @param x A numeric vector (each element represents a number of bytes). |
| 288 |
#' @param units,... Passed to [`format()`][format.object_size]. |
| 289 |
#' @return A character vector. |
| 290 |
#' @export |
| 291 |
#' @examples |
| 292 |
#' xfun::format_bytes(c(1, 1024, 2000, 1e6, 2e8)) |
| 293 |
#' xfun::format_bytes(c(1, 1024, 2000, 1e6, 2e8), units = 'KB') |
| 294 |
format_bytes = function(x, units = 'auto', ...) { |
| 295 |
vapply(x, function(b) { |
| 296 |
format(structure(b, class = 'object_size'), units = units, ...) |
| 297 |
}, character(1)) |
| 298 |
} |
| 299 |
|
| 300 |
# get the function name of the parent call |
| 301 |
func_name = function(which = 1) { |
| 302 |
x = sys.call(which)[[1]] |
| 303 |
deparse(x)[1] |
| 304 |
} |
| 305 |
|
| 306 |
# evaluate an expression with an error handler; originally this was for knitr to |
| 307 |
# output error location but can also be useful for other applications |
| 308 |
handle_error = function( |
| 309 |
expr, handler, label = '', fun = getOption('xfun.handle_error.loc_fun') |
| 310 |
) { |
| 311 |
on.exit(if (!ok) { |
| 312 |
loc = if (is.function(fun)) trimws(fun(label)) else '' |
| 313 |
m = handler(loc) |
| 314 |
message(one_string(m)) |
| 315 |
}) |
| 316 |
ok = FALSE |
| 317 |
expr # evaluate now |
| 318 |
ok = TRUE |
| 319 |
expr # won't be evaluated again |
| 320 |
} |
| 321 |
|
| 322 |
# a shorthand for rm(list =, envir =) |
| 323 |
rm_vars = function(x, envir, ...) { |
| 324 |
rm(list = intersect(x, ls(envir, all.names = TRUE)), envir = envir, ...) |
| 325 |
} |
| 326 |
|
| 327 |
is_timeout = function(t0, timeout) { |
| 328 |
difftime(Sys.time(), t0, units = 'secs') > timeout |
| 329 |
} |