Title: | Utility Functions |
---|---|
Description: | Base R sometimes requires verbose statements for simple, often recurring tasks, such as printing text without trailing space, ending with newline. This package aims at providing shorthands for such tasks. |
Authors: | Tobias Schmidt [aut, cre] |
Maintainer: | Tobias Schmidt <[email protected]> |
License: | MIT + file LICENSE |
Version: | 2.8.0 |
Built: | 2024-11-08 04:58:51 UTC |
Source: | https://github.com/toscm/toscutil |
Returns the name of a calling function as string, i.e. if function g
calls function f
and function f
calls caller(2)
, then string "g"
is returned.
caller(n = 1)
caller(n = 1)
n |
How many frames to go up in the call stack |
Be careful when using caller(n)
as input to other functions. Due to R's non-standard-evaluation (NES) mechanism it is possible that the function is not executed directly by that function but instead passed on to other functions, i.e. the correct number of frames to go up cannot be predicted a priori. Solutions are to evaluate the function first, store the result in a variable and then pass the variable to the function or to just try out the required number of frames to go up in an interactive session. For further examples see section Examples.
Name of the calling function
# Here we want to return a list of all variables created inside a function f <- function(a = 1, b = 2) { x <- 3 y <- 4 return(locals(without = formalArgs(caller(4)))) # We need to go 4 frames up, to catch the formalArgs of `f`, because the # `caller(4)` argument is not evaluated directly be `formalArgs`. } f() # returns either list(x = 3, y = 4) or list(y = 4, x = 3) # The same result could have been achieved as follows g <- function(a = 1, b = 2) { x <- 3 y <- 4 func <- caller(1) return(locals(without = c("func", formalArgs(func)))) } g() # returns either list(x = 3, y = 4) or list(y = 4, x = 3)
# Here we want to return a list of all variables created inside a function f <- function(a = 1, b = 2) { x <- 3 y <- 4 return(locals(without = formalArgs(caller(4)))) # We need to go 4 frames up, to catch the formalArgs of `f`, because the # `caller(4)` argument is not evaluated directly be `formalArgs`. } f() # returns either list(x = 3, y = 4) or list(y = 4, x = 3) # The same result could have been achieved as follows g <- function(a = 1, b = 2) { x <- 3 y <- 4 func <- caller(1) return(locals(without = c("func", formalArgs(func)))) } g() # returns either list(x = 3, y = 4) or list(y = 4, x = 3)
Like classic capture.output()
, but with additional arguments collapse
and trim
.
capture.output2(..., collapse = "\n", trim = FALSE)
capture.output2(..., collapse = "\n", trim = FALSE)
... |
Arguments passed on to |
collapse |
If |
trim |
If |
If collapse
is TRUE
or "\n"
, a character vector of length 1. Else, a character vector of length n
, where n
corresponds to the number of lines outputted by the expression passed to capture.output()
.
x <- capture.output2(str(list(a = 1, b = 2, c = 1:3))) cat2(x)
x <- capture.output2(str(list(a = 1, b = 2, c = 1:3))) cat2(x)
Same as cat
but with an additional argument end
,
which gets printed after all other elements. Inspired by pythons print
command.
Warning: this function is deprecated and should no longer be used. The function is guaranteed to be available as part of the package until the end of 2023 but might removed at any time after 31.12.2023.
cat0(..., sep = "", end = "")
cat0(..., sep = "", end = "")
... |
objects passed on to cat |
sep |
a character vector of strings to append after each element |
end |
a string to print after all other elements |
No return value, called for side effects
cat0("hello", "world") # prints "helloworld" (without newline)
cat0("hello", "world") # prints "helloworld" (without newline)
Same as cat
but with an additional argument end
,
which gets printed after all other elements. Inspired by pythons print
command.
Warning: this function is deprecated and should no longer be used. The function is guaranteed to be available as part of the package until the end of 2023 but might removed at any time after 31.12.2023.
cat0n(..., sep = "", end = "\n")
cat0n(..., sep = "", end = "\n")
... |
objects passed on to cat |
sep |
a character vector of strings to append after each element |
end |
a string to print after all other elements |
No return value, called for side effects
cat0n("hello", "world") # prints "helloworld\n"
cat0n("hello", "world") # prints "helloworld\n"
Same as base::cat()
but with an additional argument end
, which gets printed after all other elements. Inspired by pythons print
command.
cat2( ..., sep = " ", end = "\n", file = "", append = FALSE, fill = FALSE, labels = NULL )
cat2( ..., sep = " ", end = "\n", file = "", append = FALSE, fill = FALSE, labels = NULL )
... |
R objects (see 'Details' for the types of objects allowed). |
sep |
a character vector of strings to append after each element. |
end |
a string to print after all other elements. |
file |
A connection, or a character string naming the file to print to. If |
append |
logical. Only used if the argument |
fill |
a logical or (positive) numeric controlling how the output is broken into successive lines. If |
labels |
character vector of labels for the lines printed. Ignored if |
No return value, called for side effects
x <- 1 cat("x:", x, "\n") # prints 'Number: 1 \n' (with a space between 1 and \n) cat2("x:", x) # prints 'Number: 1\n' (without space)
x <- 1 cat("x:", x, "\n") # prints 'Number: 1 \n' (with a space between 1 and \n) cat2("x:", x) # prints 'Number: 1\n' (without space)
Same as cat(sprintf(fmt, ...))
catf(fmt, ..., file = "", append = FALSE, fill = FALSE, labels = NULL)
catf(fmt, ..., file = "", append = FALSE, fill = FALSE, labels = NULL)
fmt |
A character vector of format strings, each of up to 8192 bytes. |
... |
Up to 100 values to be passed into |
file |
A connection, or a character string naming the file to print to. If |
append |
logical. Only used if the argument |
fill |
a logical or (positive) numeric controlling how the output is broken into successive lines. If |
labels |
character vector of labels for the lines printed. Ignored if |
No return value, called for side effects
catf("A%dB%sC", 2, "asdf") # prints "A2BasdfC"
catf("A%dB%sC", 2, "asdf") # prints "A2BasdfC"
Same as cat2(sprintf(fmt, ...))
Warning: this function is deprecated and should no longer be used. The function is guaranteed to be available as part of the package until the end of 2023 but might removed at any time after 31.12.2023.
catfn( fmt, ..., end = "\n", file = "", sep = " ", fill = FALSE, labels = NULL, append = FALSE )
catfn( fmt, ..., end = "\n", file = "", sep = " ", fill = FALSE, labels = NULL, append = FALSE )
fmt |
passed on to |
... |
passed on to |
end |
passed on to |
file |
passed on to |
sep |
passed on to |
fill |
passed on to |
labels |
passed on to |
append |
passed on to |
No return value, called for side effects
catfn("A%dB%sC", 2, "asdf") # prints "A2BasdfC\n"
catfn("A%dB%sC", 2, "asdf") # prints "A2BasdfC\n"
Same as cat
but with an additional argument end
,
which gets printed after all other elements. Inspired by pythons print
command.
Warning: this function is deprecated and should no longer be used. The function is guaranteed to be available as part of the package until the end of 2023 but might removed at any time after 31.12.2023.
catn(..., sep = " ", end = "\n")
catn(..., sep = " ", end = "\n")
... |
objects passed on to cat |
sep |
a character vector of strings to append after each element |
end |
a string to print after all other elements |
No return value, called for side effects
catn("hello", "world") # prints "hello world\n"
catn("hello", "world") # prints "hello world\n"
Same as cat
but with an additional argument end
,
which gets printed after all other elements. Inspired by pythons print
command.
Warning: this function is deprecated and should no longer be used. The function is guaranteed to be available as part of the package until the end of 2023 but might removed at any time after 31.12.2023.
catnn(..., sep = "\n", end = "\n")
catnn(..., sep = "\n", end = "\n")
... |
objects passed on to cat |
sep |
a character vector of strings to append after each element |
end |
a string to print after all other elements |
No return value, called for side effects
catnn("hello", "world") # prints "hello\nworld\n"
catnn("hello", "world") # prints "hello\nworld\n"
Same as cat
but with an additional argument end
,
which gets printed after all other elements. Inspired by pythons print
command.
Warning: this function is deprecated and should no longer be used. The function is guaranteed to be available as part of the package until the end of 2023 but might removed at any time after 31.12.2023.
catsn(..., sep = " ", end = "\n")
catsn(..., sep = " ", end = "\n")
... |
objects passed on to cat |
sep |
a character vector of strings to append after each element |
end |
a string to print after all other elements |
No return value, called for side effects
catsn("hello", "world") # prints "hello world\n"
catsn("hello", "world") # prints "hello world\n"
Lists all documented functions in a package and checks their documentation elements for potential issues. The following checks are performed:
Title is present and doesn't start with regex "Function".
Description is present and doesn't start with "This function".
Value is present.
Example is present.
check_pkg_docs(pkg = NULL)
check_pkg_docs(pkg = NULL)
pkg |
The package name. If NULL, the package name is inferred from the DESCRIPTION file in the current directory or any parent directory. If no DESCRIPTION file is found, the function stops with an error message. |
Returns a dataframe with columns title
, description
, value
, examples
and rows corresponding to the documented functions in the package. Each cell contains a string describing the check result for the corresponding documentation element of that function.
df <- check_pkg_docs("tools") try(df <- check_pkg_docs())
df <- check_pkg_docs("tools") try(df <- check_pkg_docs())
config_dir
returns the absolute, normalized path to the configuration directory of a program/package/app based on an optional app-specific commandline argument, an optional app-specific environment variable and the XDG Base Directory Specification
config_dir( app_name, cl_arg = commandArgs()[grep("--config-dir", commandArgs()) + 1], env_var = Sys.getenv(toupper(paste0(app_name, "_config_dir()"))), create = FALSE, sep = "/" )
config_dir( app_name, cl_arg = commandArgs()[grep("--config-dir", commandArgs()) + 1], env_var = Sys.getenv(toupper(paste0(app_name, "_config_dir()"))), create = FALSE, sep = "/" )
app_name |
Name of the program/package/app |
cl_arg |
Value of app specific commandline parameter |
env_var |
Value of app specific environment variable |
create |
whether to create returned path, if it doesn't exists yet |
sep |
Path separator to be used on Windows |
The following algorithm is used to determine the location of the configuration directory for application $app_name
:
If parameter cl_arg
is a non-empty string, return it
Else, if parameter env_var
is a non-empty string, return it
Else, if environment variable (EV) XDG_CONFIG_HOME
exists, return
$XDG_CONFIG_HOME/$app_name
Else, if EV HOME
exists, return $HOME/.config/{app_name}
Else, if EV USERPROFILE
exists, return
$USERPROFILE/.config/{app_name}
Else, return $WD/.config/{app-name}
where $WD
equals the current working directory and the notation $VAR
is used to specify the value of a parameter or environment variable VAR.
Normalized path to the configuration directory of $app_name
.
data_dir()
, config_file()
, xdg_config_home()
config_dir("myApp")
config_dir("myApp")
config_file
returns the absolute, normalized path to the configuration file of a program/package/app based on an optional app-specific commandline argument, an optional app-specific environment variable and the XDG Base Directory Specification
config_file( app_name, file_name, cl_arg = commandArgs()[grep("--config-file", commandArgs()) + 1], env_var = "", sep = "/", copy_dir = norm_path(xdg_config_home(), app_name), fallback_path = NULL )
config_file( app_name, file_name, cl_arg = commandArgs()[grep("--config-file", commandArgs()) + 1], env_var = "", sep = "/", copy_dir = norm_path(xdg_config_home(), app_name), fallback_path = NULL )
app_name |
Name of the program/package/app |
file_name |
Name of the configuration file |
cl_arg |
Value of app specific commandline parameter |
env_var |
Value of app specific environment variable |
sep |
Path separator to be used on Windows |
copy_dir |
Path to directory where |
fallback_path |
Value to return as fallback (see details) |
The following algorithm is used to determine the location of $file_name
:
If $cl_arg
is a non-empty string, return it
Else, if $env_var
is a non-empty string, return it
Else, if $PWD/.config/$app_name
exists, return it
Else, if $XDG_CONFIG_HOME/$app_name/$file_name
exists, return it
Else, if $HOME/.config/$app_name/$file_name
exists, return it
Else, if $USERPROFILE/.config/$app_name/$file_name
exists, return it
Else, if $copy_dir
is non-empty string and $fallback_path
is a path
to an existing file, then try to copy $fallback_path
to
copy_dir
/$file_name
and return copy_dir
/$file_name
(Note, that
in case $copy_dir is a non-valid path, the function will throw an error.)
Else, return $fallback_path
Normalized path to the configuration file of $app_name
.
config_dir()
, xdg_config_home()
config_dir("myApp")
config_dir("myApp")
Similar to head()
and tail()
, but returns n
rows/cols
from each side of x
(i.e. the corners of x
).
corn(x, n = 2L)
corn(x, n = 2L)
x |
matrix like object |
n |
number of cols/rows from each corner to return |
x[c(1:n, N-n:N), c(1:n, N-n:N)]
corn(matrix(1:10000, 100))
corn(matrix(1:10000, 100))
data_dir
returns the absolute, normalized path to the data directory of a program/package/app based on an optional app-specific commandline argument, an optional app-specific environment variable and the XDG Base Directory Specification
data_dir( app_name, cl_arg = commandArgs()[grep("--data-dir", commandArgs()) + 1], env_var = Sys.getenv(toupper(paste0(app_name, "_DATA_DIR"))), create = FALSE, sep = "/" )
data_dir( app_name, cl_arg = commandArgs()[grep("--data-dir", commandArgs()) + 1], env_var = Sys.getenv(toupper(paste0(app_name, "_DATA_DIR"))), create = FALSE, sep = "/" )
app_name |
Name of the program/package/app |
cl_arg |
Value of app specific commandline parameter |
env_var |
Value of app specific environment variable |
create |
whether to create returned path, if it doesn't exists yet |
sep |
Path separator to be used on Windows |
The following algorithm is used to determine the location of the data directory for application $app_name
:
If parameter $cl_arg
is a non-empty string, return cl_arg
Else, if parameter $env_var
is a non-empty string, return $env_var
Else, if environment variable (EV) $XDG_DATA_HOME
exists, return
$XDG_DATA_HOME/$app_name
Else, if EV $HOME
exists, return $HOME/.local/share/$app_name
Else, if EV $USERPROFILE
exists, return
$USERPROFILE/.local/share/$app_name
Else, return $WD/.local/share
Normalized path to the data directory of $app_name
.
data_dir("myApp")
data_dir("myApp")
A minimal docstring template
DOCSTRING_TEMPLATE
DOCSTRING_TEMPLATE
A single string, i.e. a character vector of length 1.
cat(DOCSTRING_TEMPLATE)
cat(DOCSTRING_TEMPLATE)
Like classic dput()
, but instead of writing to stdout, the text representation is returned as string.
dput2(..., collapse = " ", trim = TRUE)
dput2(..., collapse = " ", trim = TRUE)
... |
Arguments passed on to |
collapse |
Character to use for collapsing the lines. |
trim |
If |
If collapse == '\n'
, a character vector of length 1. Else, a character vector of length n
, where n
corresponds to the number of lines outputted by classic dput()
.
# Classic dput prints directly to stdout x <- iris[1, ] dput(x) # Traditional formatting using dput2 y <- dput2(x, collapse = "\n", trim = FALSE) cat2(y) # Single line formatting z <- dput2(x) cat2(z)
# Classic dput prints directly to stdout x <- iris[1, ] dput(x) # Traditional formatting using dput2 y <- dput2(x, collapse = "\n", trim = FALSE) cat2(y) # Single line formatting z <- dput2(x) cat2(z)
Provides ANSI escape codes as a named list for changing terminal text colors and style resetting. These codes can modify the foreground color and reset styles to defaults (incl. background color and text formatting).
fg
fg
A named list of ANSI escape codes for text coloring and style resetting in the terminal. Includes colors: GREY, RED, GREEN, YELLOW, BLUE, PURPLE, CYAN, WHITE, and RESET for default style restoration.
cat(fg$RED, "This text will be red.", fg$RESET, "\n") cat(fg$GREEN, "This text will be green.", fg$RESET, "\n") cat(fg$RESET, "Text back to default.", "\n")
cat(fg$RED, "This text will be red.", fg$RESET, "\n") cat(fg$GREEN, "This text will be green.", fg$RESET, "\n") cat(fg$RESET, "Text back to default.", "\n")
Searches for a DESCRIPTION file starting from the current or specified directory and moving upwards through the directory hierarchy until the file is found or the root directory is reached.
find_description_file(start_dir = getwd())
find_description_file(start_dir = getwd())
start_dir |
The starting directory for the search. Defaults to the current working directory. |
The path to the DESCRIPTION file if found. If not found, the function stops with an error message.
# Start search from a specific directory graphics_pkg_dir <- system.file(package = "graphics") find_description_file(graphics_pkg_dir) ## Not run: # Below example will only work if executed from a package directory find_description_file() ## End(Not run)
# Start search from a specific directory graphics_pkg_dir <- system.file(package = "graphics") find_description_file(graphics_pkg_dir) ## Not run: # Below example will only work if executed from a package directory find_description_file() ## End(Not run)
Returns the function environment as list. Raises an error when called outside a function. By default, objects specified as arguments are removed from the environment.
function_locals(without = c(), strip_function_args = TRUE)
function_locals(without = c(), strip_function_args = TRUE)
without |
character vector of symbols to exclude |
strip_function_args |
Whether to exclude symbols with the same name as the function arguments |
The order of the symbols in the returned list is arbitrary.
The function environment as list
f <- function(a = 1, b = 2) { x <- 3 y <- 4 return(function_locals()) } all.equal(setdiff(f(), list(x = 3, y = 4)), list())
f <- function(a = 1, b = 2) { x <- 3 y <- 4 return(function_locals()) } all.equal(setdiff(f(), list(x = 3, y = 4)), list())
The roxygen2 package makes it possible to write documentation for R functions directly above the corresponding function. This function can be used to retrieve the full documentation string (docstring).
get_docstring(content, func, collapse = TRUE, template = DOCSTRING_TEMPLATE)
get_docstring(content, func, collapse = TRUE, template = DOCSTRING_TEMPLATE)
content |
R code as string. |
func |
Name of function to get docstring for. |
collapse |
Whether to collapse all docstring into a single string. |
template |
String to return in case no docstring could be found. |
A character vector of length 1 containing either the docstring or the empty string (in case no documentation could be detected).
uri <- system.file("testfiles/funcs.R", package = "toscutil") content <- readLines(uri) func <- "f2" get_docstring(content, func) get_docstring(content, func, collapse = TRUE)
uri <- system.file("testfiles/funcs.R", package = "toscutil") content <- readLines(uri) func <- "f2" get_docstring(content, func) get_docstring(content, func, collapse = TRUE)
Returns the arguments of a function from a valid R file.
get_formals(uri, content, func)
get_formals(uri, content, func)
uri |
Path to R file. |
content |
R code as string. |
func |
Function name. If a function is defined multiple times inside the provided file, only the last occurence will be considered. |
A named character vector as returned by formals()
.
uri <- system.file("testfiles/funcs.R", package = "toscutil") content <- readLines(uri) func <- "f2" if (requireNamespace("languageserver", quietly = TRUE)) { get_formals(uri, content, func) }
uri <- system.file("testfiles/funcs.R", package = "toscutil") content <- readLines(uri) func <- "f2" if (requireNamespace("languageserver", quietly = TRUE)) { get_formals(uri, content, func) }
Lists all documented functions in a package together with some of their documentation elements as raw text. Only works for installed packages.
get_pkg_docs(pkg = NULL, unload = TRUE, reload = TRUE)
get_pkg_docs(pkg = NULL, unload = TRUE, reload = TRUE)
pkg |
The package name. If NULL, the package name is inferred from the DESCRIPTION file in the current directory or any parent directory. If no DESCRIPTION file is found, the function stops with an error message. |
unload |
Whether to unload a potential currently developed package using |
reload |
Whether to reload the package using |
Returns a dataframe with columns title
, description
, value
, examples
and rows corresponding to the documented functions in the package.
df <- get_pkg_docs("tools") nchars <- as.data.frame(apply(df, 2, function(col) sapply(col, nchar))) head(nchars)
df <- get_pkg_docs("tools") nchars <- as.data.frame(apply(df, 2, function(col) sapply(col, nchar))) head(nchars)
Return full path to current file directory
getfd( on.error = stop("No file sourced. Maybe you're in an interactive shell?", call. = FALSE), winslash = "/" )
getfd( on.error = stop("No file sourced. Maybe you're in an interactive shell?", call. = FALSE), winslash = "/" )
on.error |
Expression to use if the current file directory cannot be determined. In that case, |
winslash |
Path separator to use for windows |
Current file directory as string
getfd(on.error = getwd()) ## Not run: getfd() ## End(Not run)
getfd(on.error = getwd()) ## Not run: getfd() ## End(Not run)
Find the project root directory by traversing the current working directory filepath upwards until a given set of files is found.
getpd(root.files = c(".git", "DESCRIPTION", "NAMESPACE"))
getpd(root.files = c(".git", "DESCRIPTION", "NAMESPACE"))
root.files |
if any of these files is found in a parent folder, the path to that folder is returned |
getpd
returns the absolute, normalized project root directory as string. The forward slash is used as path separator (independent of the OS).
local({ base_pkg_root_dir <- system.file(package = "base") base_pkg_R_dir <- file.path(base_pkg_root_dir, "R") owd <- setwd(base_pkg_R_dir); on.exit(setwd(owd)) getpd() })
local({ base_pkg_root_dir <- system.file(package = "base") base_pkg_R_dir <- file.path(base_pkg_root_dir, "R") owd <- setwd(base_pkg_R_dir); on.exit(setwd(owd)) getpd() })
Returns the help text for the specified topic formatted either as plain text, html or latex.
help2(topic, format = "text", package = NULL)
help2(topic, format = "text", package = NULL)
topic |
character, the topic for which to return the help text. See argument |
format |
character, either |
package |
character, the package for which to return the help text. This argument will be ignored if topic is specified. Package must be attached to the search list first, e.g. by calling |
The help text for the specified topic in the specified format as string.
htm <- help2("sum", "html") txt <- help2(topic = "sum", format = "text") cat2(txt)
htm <- help2("sum", "html") txt <- help2(topic = "sum", format = "text") cat2(txt)
Returns normalized value of environment variable USERPROFILE, if defined, else value of HOME.
home(winslash = "/")
home(winslash = "/")
winslash |
path separator to be used on Windows (passed on to |
normalized value of environment variable USERPROFILE, if defined, else value of HOME.
home()
home()
ifthen(a, b, c, d, e, f, ...)
== if (a) b else if (c) d else if (e) f
ifthen(...)
ifthen(...)
... |
pairs of checks and corresponding return values |
ifelse
returns the first value for which the corresponding
statement evaluates to TRUE
x <- 2 y <- 2 z <- 1 ifthen(x == 0, "foo", y == 0, "bar", z == 1, "this string gets returned")
x <- 2 y <- 2 z <- 1 ifthen(x == 0, "foo", y == 0, "bar", z == 1, "this string gets returned")
Returns TRUE
if x
is either FALSE
, 0
, NULL
, NA
and
empty lists or an empty string. Inspired by python's
bool.
is.none(x)
is.none(x)
x |
object to test |
TRUE
if x
is FALSE
, 0, NULL
, NA
, an empty list or an empty
string. Else FALSE.
is.none(FALSE) # TRUE is.none(0) # TRUE is.none(1) # FALSE is.none(NA) # TRUE is.none(list()) # TRUE is.none("") # TRUE is.none(character()) # TRUE is.none(numeric()) # TRUE is.none(logical()) # TRUE
is.none(FALSE) # TRUE is.none(0) # TRUE is.none(1) # FALSE is.none(NA) # TRUE is.none(list()) # TRUE is.none("") # TRUE is.none(character()) # TRUE is.none(numeric()) # TRUE is.none(logical()) # TRUE
Return all symbols in the specified environment as list.
locals(without = c(), env = parent.frame())
locals(without = c(), env = parent.frame())
without |
Character vector. Symbols from current env to exclude. |
env |
Environment to use. Defaults to the environment from which |
Specified environment as list (without the mentioned symbols).
f <- function() { x <- 1 y <- 2 z <- 3 locals() } ret <- f() stopifnot(identical(ret, list(z = 3, y = 2, x = 1)))
f <- function() { x <- 1 y <- 2 z <- 3 locals() } ret <- f() stopifnot(identical(ret, list(z = 3, y = 2, x = 1)))
Like normal list()
, except that unnamed elements are automatically named according to their symbol
named(...)
named(...)
... |
List elements |
Object of type list
with names attribute set
a <- 1:10 b <- "helloworld" l1 <- list(a, b) names(l1) <- c("a", "b") l2 <- named(a, b) stopifnot(identical(l1, l2)) l3 <- list(z = a, b = b) l4 <- named(z = a, b) stopifnot(identical(l3, l4))
a <- 1:10 b <- "helloworld" l1 <- list(a, b) names(l1) <- c("a", "b") l2 <- named(a, b) stopifnot(identical(l1, l2)) l3 <- list(z = a, b = b) l4 <- named(z = a, b) stopifnot(identical(l3, l4))
Shortcut for normalizePath(file.path(...), winslash = sep, mustWork = FALSE)
norm_path(..., sep = "/")
norm_path(..., sep = "/")
... |
Parts used to construct the path |
sep |
Path separator to be used on Windows |
Normalized path constructed from ...
norm_path("C:/Users/max", "a\\b", "c") # returns C:/Users/max/a/b/c norm_path("a\\b", "c") # return <current-working-dir>/a/b/c
norm_path("C:/Users/max", "a\\b", "c") # returns C:/Users/max/a/b/c norm_path("a\\b", "c") # return <current-working-dir>/a/b/c
Returns the current system time as a string in the format YYYY-MM-DD hh:mm:ss[.XX][ TZ]
. Square brackets indicate optional parts of the string, 'XX' stands for milliseconds and 'TZ' for 'Timezone'.
now(usetz = TRUE, color = NULL, digits.sec = 0) now_ms(usetz = TRUE, color = NULL, digits.sec = 2)
now(usetz = TRUE, color = NULL, digits.sec = 0) now_ms(usetz = TRUE, color = NULL, digits.sec = 2)
usetz |
Logical, indicating whether to include the timezone in the output. |
color |
Optional color to use for the timestamp. This parameter is only effective if the output is directed to a terminal that supports color, which is checked via |
digits.sec |
Integer, the number of digits to include for seconds. Default is 0. |
For now
, the current system time as a string in the format YYYY-MM-DD hh:mm:ss TZ
.
For now_ms
, the format is YYYY-MM-DD hh:mm:ss.XX TZ
, where XX represents milliseconds.
now() # "2021-11-27 19:19:31 CEST" now_ms() # "2022-06-30 07:14:26.82 CEST" now(usetz = FALSE) # "2022-06-30 07:14:26.82" now(color = fg$GREY) # "\033[1;30m2024-06-27 14:41:20 CEST\033[0m"
now() # "2021-11-27 19:19:31 CEST" now_ms() # "2022-06-30 07:14:26.82 CEST" now(usetz = FALSE) # "2022-06-30 07:14:26.82" now(color = fg$GREY) # "\033[1;30m2024-06-27 14:41:20 CEST\033[0m"
Like rlang::%||%()
but also checks for empty lists and empty strings.
x %none% y
x %none% y
x |
object to test |
y |
object to return if |
Returns y
if is.none(x)
else x
FALSE %none% 2 # returns 2 0 %none% 2 # returns 2 NA %none% 2 # returns 2 list() %none% 2 # returns 2 "" %none% 2 # returns 2 1 %none% 2 # returns 1
FALSE %none% 2 # returns 2 0 %none% 2 # returns 2 NA %none% 2 # returns 2 list() %none% 2 # returns 2 "" %none% 2 # returns 2 1 %none% 2 # returns 1
Interprets the provided numeric vector as linear model and uses
it to generate predictions. If an element of the numeric vector has the name
"Intercept"
this element is treated as the intercept of the linear model.
## S3 method for class 'numeric' predict(object, newdata, ...)
## S3 method for class 'numeric' predict(object, newdata, ...)
object |
Named numeric vector of beta values. If an element is named "Intercept", that element is interpreted as model intercept. |
newdata |
Matrix with samples as rows and features as columns. |
... |
further arguments passed to or from other methods |
Named numeric vector of predicted scores
X <- matrix(1:4, 2, 2, dimnames = list(c("s1", "s2"), c("a", "b"))) b <- c(Intercept = 3, a = 2, b = 1) predict(b, X)
X <- matrix(1:4, 2, 2, dimnames = list(c("s1", "s2"), c("a", "b"))) b <- c(Intercept = 3, a = 2, b = 1) predict(b, X)
Reads the DESCRIPTION file of an R package and converts it into a list where each element corresponds to a field in the DESCRIPTION file.
read_description_file(p = NULL)
read_description_file(p = NULL)
p |
The path to the DESCRIPTION file. If |
A list where each element is a field from the DESCRIPTION file.
# Read DECRIPTION file from a specific path graphics_pkg_dir <- system.file(package = "graphics") graphics_pkg_descfile <- find_description_file(graphics_pkg_dir) desc_list <- read_description_file(graphics_pkg_descfile) str(desc_list) ## Not run: # Below example will only work if executed from a package directory read_description_file() ## End(Not run)
# Read DECRIPTION file from a specific path graphics_pkg_dir <- system.file(package = "graphics") graphics_pkg_descfile <- find_description_file(graphics_pkg_dir) desc_list <- read_description_file(graphics_pkg_descfile) str(desc_list) ## Not run: # Below example will only work if executed from a package directory read_description_file() ## End(Not run)
Same as rm(list=ls())
rm_all()
rm_all()
No return value, called for side effects
## Not run: rm_all()
## Not run: rm_all()
Split a docstring into a head, param and tail part.
split_docstring(docstring)
split_docstring(docstring)
docstring |
Docstring of a R function as string, i.e. as character vector of length 1. |
List with 3 elements: head, param and tail.
uri <- system.file("testfiles/funcs.R", package = "toscutil") func <- "f4" content <- readLines(uri) docstring <- get_docstring(content, func) split_docstring(docstring)
uri <- system.file("testfiles/funcs.R", package = "toscutil") func <- "f4" content <- readLines(uri) docstring <- get_docstring(content, func) split_docstring(docstring)
stub()
assigns all arguments of a given function as symbols
to the specified environment (usually the current environment)
stub(func, ..., envir = parent.frame())
stub(func, ..., envir = parent.frame())
func |
function for which the arguments should be stubbed |
... |
non-default arguments of |
envir |
environment to which symbols should be assigned |
Stub is thought to be used for interactive testing and unit testing. It does not work for primitive functions.
list of symbols that are assigned to envir
f <- function(x, y = 2, z = 3) x + y + z args <- stub(f, x = 1) # assigns x = 1, y = 2 and z = 3 to current env
f <- function(x, y = 2, z = 3) x + y + z args <- stub(f, x = 1) # assigns x = 1, y = 2 and z = 3 to current env
Similar to python's sys.exit. If used interactively, code execution is stopped with an error message, giving the provided status code. If used non-interactively (e.g. through Rscript), code execution is stopped silently and the process exits with the provided status code.
sys.exit(status = 0)
sys.exit(status = 0)
status |
exitcode for R process |
No return value, called for side effects
## Not run: if (!file.exists("some.file")) { cat("Error: some.file does not exist.\n", file = stderr()) sys.exit(1) } else if (Sys.getenv("IMPORTANT_ENV") == "") { cat("Error: IMPORTANT_ENV not set.\n", file = stderr()) sys.exit(2) } else { cat("Everything good. Starting calculations...") # ... cat("Finished with success!") sys.exit(0) } ## End(Not run)
## Not run: if (!file.exists("some.file")) { cat("Error: some.file does not exist.\n", file = stderr()) sys.exit(1) } else if (Sys.getenv("IMPORTANT_ENV") == "") { cat("Error: IMPORTANT_ENV not set.\n", file = stderr()) sys.exit(2) } else { cat("Everything good. Starting calculations...") # ... cat("Finished with success!") sys.exit(0) } ## End(Not run)
Traces all function calls from a package and writes them to file
with timestamps and callstack depth. Should always be used in combination with untrace_package()
to untrace the package after use. For example trace_package("graphics"); on.exit(untrace_package("graphics")
. See examples for more details.
trace_package( pkg, file = stdout(), max = Inf, funign = character(), opsign = TRUE, dotign = TRUE, silent = TRUE, exitmsg = "exit" )
trace_package( pkg, file = stdout(), max = Inf, funign = character(), opsign = TRUE, dotign = TRUE, silent = TRUE, exitmsg = "exit" )
pkg |
Package name to trace. |
file |
File to write to. |
max |
Maximum depth of callstack to print. |
funign |
Functions to ignore. |
opsign |
Whether to ignore operators. |
dotign |
Whether to ignore functions starting with a dot. |
silent |
Whether to suppress messages. |
exitmsg |
Message to print on function exits. |
Some function define their own on.exit()
handlers with option add = FALSE
. For those functions, exit tracing is impossible (as described in trace()
). For now those functions have to be detected and ignored manually by the user using argument funign
.
No return value, called for side effects
## Not run: # Trace all function from the graphics package, except for `plot.default` # as it defines its own on.exit() handler, i.e. exit tracing is impossible. local({ trace_package("graphics", funign = "plot.default") on.exit(untrace_package("graphics"), add = TRUE) plot(1:10) }) ## End(Not run)
## Not run: # Trace all function from the graphics package, except for `plot.default` # as it defines its own on.exit() handler, i.e. exit tracing is impossible. local({ trace_package("graphics", funign = "plot.default") on.exit(untrace_package("graphics"), add = TRUE) plot(1:10) }) ## End(Not run)
Removes tracing from all function calls in a package that were previously traced by trace_package()
.
untrace_package(pkg)
untrace_package(pkg)
pkg |
Package name to untrace. |
This function reverses the effects of trace_package
by removing all tracing from the specified package's functions.
No return value, called for side effects
## Not run: local({ trace_package("graphics", funign = "plot.default") on.exit(untrace_package("graphics"), add = TRUE) plot(1:10) }) ## End(Not run)
## Not run: local({ trace_package("graphics", funign = "plot.default") on.exit(untrace_package("graphics"), add = TRUE) plot(1:10) }) ## End(Not run)
The roxygen2 package makes it possible to write documentation for R functions directly above the corresponding function. This function can be used to update the parameter list of a documentation string (docstring) of a valid function of a valid R file. The update is done by comparing the currently listed parameters with the actual function parameters. Outdated parameters are removed and missing parameters are added to the docstring.
update_docstring(uri, func, content = NULL)
update_docstring(uri, func, content = NULL)
uri |
Path to R file. |
func |
Function name. If a function is defined multiple times inside the provided file, only the last occurence will be considered. |
content |
R code as string. If provided, uri is ignored. |
A character vector of length 1 containing the updated docstring.
uri <- system.file("testfiles/funcs.R", package = "toscutil") func <- "f4" update_docstring(uri, func)
uri <- system.file("testfiles/funcs.R", package = "toscutil") func <- "f4" update_docstring(uri, func)
Return value for XDG_CONFIG_HOME as defined by the XDG Base Directory Specification
xdg_config_home(sep = "/", fallback = normalizePath(getwd(), winslash = sep))
xdg_config_home(sep = "/", fallback = normalizePath(getwd(), winslash = sep))
sep |
Path separator to be used on Windows |
fallback |
Value to return as fallback (see details) |
The following algorithm is used to determine the returned path:
If environment variable (EV) XDG_CONFIG_HOME
exists, return its value
Else, if EV HOME
exists, return $HOME/.config
Else, if EV USERPROFILE
exists, return $USERPROFILE/.config
Else, return $fallback
xdg_config_home()
xdg_config_home()
Return value for XDG_DATA_HOME as defined by the XDG Base Directory Specification
xdg_data_home(sep = "/", fallback = normalizePath(getwd(), winslash = sep))
xdg_data_home(sep = "/", fallback = normalizePath(getwd(), winslash = sep))
sep |
Path separator to be used on Windows |
fallback |
Value to return as fallback (see details) |
The following algorithm is used to determine the returned path:
If environment variable (EV) $XDG_DATA_HOME
exists, return its value
Else, if EV $HOME
exists, return $HOME/.local/share
Else, if EV $USERPROFILE
exists, return $USERPROFILE/.local/share
Else, return $fallback
xdg_data_home()
xdg_data_home()