| Title: | Some Utilities for Developing Data Science Software |
|---|---|
| Description: | A collection of general-purpose helper functions that I (and maybe others) find useful when developing data science software. Includes tools for simulation, data transformation, input validation, and more. |
| Authors: | Lennart Oelschläger [aut, cre] |
| Maintainer: | Lennart Oelschläger <[email protected]> |
| License: | GPL (>= 3) |
| Version: | 0.7.6.9000 |
| Built: | 2026-06-03 06:53:51 UTC |
| Source: | https://github.com/loelschlaeger/oeli |
These functions check whether the input fulfills the properties of a correlation matrix.
check_correlation_matrix(x, dim = NULL, tolerance = sqrt(.Machine$double.eps)) assert_correlation_matrix( x, dim = NULL, tolerance = sqrt(.Machine$double.eps), .var.name = checkmate::vname(x), add = NULL ) test_correlation_matrix(x, dim = NULL, tolerance = sqrt(.Machine$double.eps))check_correlation_matrix(x, dim = NULL, tolerance = sqrt(.Machine$double.eps)) assert_correlation_matrix( x, dim = NULL, tolerance = sqrt(.Machine$double.eps), .var.name = checkmate::vname(x), add = NULL ) test_correlation_matrix(x, dim = NULL, tolerance = sqrt(.Machine$double.eps))
x |
[ |
dim |
[ |
tolerance |
[ |
.var.name |
[ |
add |
[ |
Same as documented in check_matrix.
Other matrix helpers:
check_covariance_matrix(),
check_one_hot_matrix(),
check_transition_probability_matrix(),
cov_to_chol(),
diff_cov(),
insert_matrix_column(),
matrix_diagonal_indices(),
matrix_indices(),
sample_correlation_matrix(),
sample_covariance_matrix(),
sample_transition_probability_matrix(),
stationary_distribution()
M <- matrix(c(1, 0.9, 0.9, 0.9, 1, -0.9, 0.9, -0.9, 1), nrow = 3) check_correlation_matrix(M) test_correlation_matrix(M) ## Not run: assert_correlation_matrix(M) ## End(Not run)M <- matrix(c(1, 0.9, 0.9, 0.9, 1, -0.9, 0.9, -0.9, 1), nrow = 3) check_correlation_matrix(M) test_correlation_matrix(M) ## Not run: assert_correlation_matrix(M) ## End(Not run)
These functions check whether the input fulfills the properties of a covariance matrix.
check_covariance_matrix(x, dim = NULL, tolerance = sqrt(.Machine$double.eps)) assert_covariance_matrix( x, dim = NULL, tolerance = sqrt(.Machine$double.eps), .var.name = checkmate::vname(x), add = NULL ) test_covariance_matrix(x, dim = NULL, tolerance = sqrt(.Machine$double.eps))check_covariance_matrix(x, dim = NULL, tolerance = sqrt(.Machine$double.eps)) assert_covariance_matrix( x, dim = NULL, tolerance = sqrt(.Machine$double.eps), .var.name = checkmate::vname(x), add = NULL ) test_covariance_matrix(x, dim = NULL, tolerance = sqrt(.Machine$double.eps))
x |
[ |
dim |
[ |
tolerance |
[ |
.var.name |
[ |
add |
[ |
Same as documented in check_matrix.
Other matrix helpers:
check_correlation_matrix(),
check_one_hot_matrix(),
check_transition_probability_matrix(),
cov_to_chol(),
diff_cov(),
insert_matrix_column(),
matrix_diagonal_indices(),
matrix_indices(),
sample_correlation_matrix(),
sample_covariance_matrix(),
sample_transition_probability_matrix(),
stationary_distribution()
M <- matrix(c(1, 2, 3, 2, 1, 2, 3, 2, 1), nrow = 3) check_covariance_matrix(M) test_covariance_matrix(M) ## Not run: assert_covariance_matrix(M) ## End(Not run)M <- matrix(c(1, 2, 3, 2, 1, 2, 3, 2, 1), nrow = 3) check_covariance_matrix(M) test_covariance_matrix(M) ## Not run: assert_covariance_matrix(M) ## End(Not run)
These functions check whether the input is a list that contains list elements.
check_list_of_lists(x, len = NULL) assert_list_of_lists( x, len = NULL, .var.name = checkmate::vname(x), add = NULL ) test_list_of_lists(x, len = NULL)check_list_of_lists(x, len = NULL) assert_list_of_lists( x, len = NULL, .var.name = checkmate::vname(x), add = NULL ) test_list_of_lists(x, len = NULL)
x |
[ |
len |
[ |
.var.name |
[ |
add |
[ |
Same as documented in check_list.
Other list helpers:
merge_lists()
L <- list(list(1), list(2), 3) check_list_of_lists(L) test_list_of_lists(L) ## Not run: assert_list_of_lists(L) ## End(Not run)L <- list(list(1), list(2), 3) check_list_of_lists(L) test_list_of_lists(L) ## Not run: assert_list_of_lists(L) ## End(Not run)
These functions check whether a value was specified as an argument to a function.
check_missing(x) assert_missing(x) test_missing(x)check_missing(x) assert_missing(x) test_missing(x)
x |
[ |
Depending on the function prefix:
If the check is successful, assert_missing() returns x invisibly,
whereas check_missing() and test_missing() return TRUE.
If the check is not successful, assert_missing() throws an error message,
test_missing() returns FALSE, and check_missing() returns a string with
the error message.
Other package helpers:
Dictionary,
Storage,
find_namespace_calls(),
find_pkg_functions(),
identical_structure(),
input_check_response(),
match_arg(),
package_logo(),
print_data.frame(),
print_matrix(),
system_information(),
unexpected_error(),
user_confirm()
f <- function(x) { check_missing(x) } f() g <- function(x) { test_missing(x) } g() h <- function(x) { assert_missing(x) } ## Not run: h() ## End(Not run)f <- function(x) { check_missing(x) } f() g <- function(x) { test_missing(x) } g() h <- function(x) { assert_missing(x) } ## Not run: h() ## End(Not run)
These functions check whether the input is a numeric vector.
check_numeric_vector( x, lower = -Inf, upper = Inf, finite = FALSE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, typed.missing = FALSE, null.ok = FALSE ) assert_numeric_vector( x, lower = -Inf, upper = Inf, finite = FALSE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, typed.missing = FALSE, null.ok = FALSE, .var.name = checkmate::vname(x), add = NULL ) test_numeric_vector( x, lower = -Inf, upper = Inf, finite = FALSE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, typed.missing = FALSE, null.ok = FALSE )check_numeric_vector( x, lower = -Inf, upper = Inf, finite = FALSE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, typed.missing = FALSE, null.ok = FALSE ) assert_numeric_vector( x, lower = -Inf, upper = Inf, finite = FALSE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, typed.missing = FALSE, null.ok = FALSE, .var.name = checkmate::vname(x), add = NULL ) test_numeric_vector( x, lower = -Inf, upper = Inf, finite = FALSE, any.missing = TRUE, all.missing = TRUE, len = NULL, min.len = NULL, max.len = NULL, unique = FALSE, sorted = FALSE, names = NULL, typed.missing = FALSE, null.ok = FALSE )
x |
[ |
lower |
[ |
upper |
[ |
finite |
[ |
any.missing |
[ |
all.missing |
[ |
len |
[ |
min.len |
[ |
max.len |
[ |
unique |
[ |
sorted |
[ |
names |
[ |
typed.missing |
[ |
null.ok |
[ |
.var.name |
[ |
add |
[ |
Same as documented in check_numeric.
Other vector helpers:
check_probability_vector(),
chunk_vector(),
equidistant_vectors(),
insert_vector_entry(),
map_indices(),
match_numerics(),
permutations(),
split_vector_at(),
subsets(),
vector_occurrence()
x <- c(1, 2, "3") check_numeric_vector(x) test_numeric_vector(x) ## Not run: assert_numeric_vector(x) ## End(Not run)x <- c(1, 2, "3") check_numeric_vector(x) test_numeric_vector(x) ## Not run: assert_numeric_vector(x) ## End(Not run)
These functions check whether the input is a one-hot matrix, i.e., a
numeric matrix where each row contains exactly one entry equal to 1 and
all other entries equal to 0.
check_one_hot_matrix( x, nrows = NULL, ncols = NULL, tolerance = sqrt(.Machine$double.eps) ) assert_one_hot_matrix( x, nrows = NULL, ncols = NULL, tolerance = sqrt(.Machine$double.eps), .var.name = checkmate::vname(x), add = NULL ) test_one_hot_matrix( x, nrows = NULL, ncols = NULL, tolerance = sqrt(.Machine$double.eps) )check_one_hot_matrix( x, nrows = NULL, ncols = NULL, tolerance = sqrt(.Machine$double.eps) ) assert_one_hot_matrix( x, nrows = NULL, ncols = NULL, tolerance = sqrt(.Machine$double.eps), .var.name = checkmate::vname(x), add = NULL ) test_one_hot_matrix( x, nrows = NULL, ncols = NULL, tolerance = sqrt(.Machine$double.eps) )
x |
[ |
nrows |
[ |
ncols |
[ |
tolerance |
[ |
.var.name |
[ |
add |
[ |
Same as documented in check_matrix.
Other matrix helpers:
check_correlation_matrix(),
check_covariance_matrix(),
check_transition_probability_matrix(),
cov_to_chol(),
diff_cov(),
insert_matrix_column(),
matrix_diagonal_indices(),
matrix_indices(),
sample_correlation_matrix(),
sample_covariance_matrix(),
sample_transition_probability_matrix(),
stationary_distribution()
x <- matrix(c( 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ), nrow = 3, byrow = TRUE) check_one_hot_matrix(x) test_one_hot_matrix(x) ## Not run: assert_one_hot_matrix(x) ## End(Not run)x <- matrix(c( 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 ), nrow = 3, byrow = TRUE) check_one_hot_matrix(x) test_one_hot_matrix(x) ## Not run: assert_one_hot_matrix(x) ## End(Not run)
These functions check whether the input fulfills the properties of a probability matrix.
check_probability_vector(x, len = NULL, tolerance = sqrt(.Machine$double.eps)) assert_probability_vector( x, len = NULL, tolerance = sqrt(.Machine$double.eps), .var.name = checkmate::vname(x), add = NULL ) test_probability_vector(x, len = NULL, tolerance = sqrt(.Machine$double.eps))check_probability_vector(x, len = NULL, tolerance = sqrt(.Machine$double.eps)) assert_probability_vector( x, len = NULL, tolerance = sqrt(.Machine$double.eps), .var.name = checkmate::vname(x), add = NULL ) test_probability_vector(x, len = NULL, tolerance = sqrt(.Machine$double.eps))
x |
[ |
len |
[ |
tolerance |
[ |
.var.name |
[ |
add |
[ |
Same as documented in check_numeric.
Other vector helpers:
check_numeric_vector(),
chunk_vector(),
equidistant_vectors(),
insert_vector_entry(),
map_indices(),
match_numerics(),
permutations(),
split_vector_at(),
subsets(),
vector_occurrence()
p <- c(0.2, 0.3, 0.6) check_probability_vector(p) test_probability_vector(p) ## Not run: assert_probability_vector(p) ## End(Not run)p <- c(0.2, 0.3, 0.6) check_probability_vector(p) test_probability_vector(p) ## Not run: assert_probability_vector(p) ## End(Not run)
These functions check whether the input is a transition probability matrix.
check_transition_probability_matrix( x, dim = NULL, tolerance = sqrt(.Machine$double.eps) ) assert_transition_probability_matrix( x, dim = NULL, tolerance = sqrt(.Machine$double.eps), .var.name = checkmate::vname(x), add = NULL ) test_transition_probability_matrix( x, dim = NULL, tolerance = sqrt(.Machine$double.eps) )check_transition_probability_matrix( x, dim = NULL, tolerance = sqrt(.Machine$double.eps) ) assert_transition_probability_matrix( x, dim = NULL, tolerance = sqrt(.Machine$double.eps), .var.name = checkmate::vname(x), add = NULL ) test_transition_probability_matrix( x, dim = NULL, tolerance = sqrt(.Machine$double.eps) )
x |
[ |
dim |
[ |
tolerance |
[ |
.var.name |
[ |
add |
[ |
Same as documented in check_matrix.
Other matrix helpers:
check_correlation_matrix(),
check_covariance_matrix(),
check_one_hot_matrix(),
cov_to_chol(),
diff_cov(),
insert_matrix_column(),
matrix_diagonal_indices(),
matrix_indices(),
sample_correlation_matrix(),
sample_covariance_matrix(),
sample_transition_probability_matrix(),
stationary_distribution()
T <- matrix(c(0.8, 0.2, 0.1, 0.1, 0.7, 0.4, 0.1, 0.1, 0.6), nrow = 3) check_transition_probability_matrix(T) test_transition_probability_matrix(T) ## Not run: assert_transition_probability_matrix(T) ## End(Not run)T <- matrix(c(0.8, 0.2, 0.1, 0.1, 0.7, 0.4, 0.1, 0.1, 0.6), nrow = 3) check_transition_probability_matrix(T) test_transition_probability_matrix(T) ## Not run: assert_transition_probability_matrix(T) ## End(Not run)
This function either
splits a vector into n chunks of equal size (type = 1),
splits a vector into chunks of size n (type = 2).
chunk_vector(x, n, type = 1, strict = FALSE)chunk_vector(x, n, type = 1, strict = FALSE)
x |
[atomic()'] |
n |
[ |
type |
[
|
strict |
[ |
A list.
Other vector helpers:
check_numeric_vector(),
check_probability_vector(),
equidistant_vectors(),
insert_vector_entry(),
map_indices(),
match_numerics(),
permutations(),
split_vector_at(),
subsets(),
vector_occurrence()
x <- 1:12 chunk_vector(x, n = 3, type = 1) chunk_vector(x, n = 3, type = 2) try(chunk_vector(x, n = 5, strict = TRUE))x <- 1:12 chunk_vector(x, n = 3, type = 1) chunk_vector(x, n = 3, type = 2) try(chunk_vector(x, n = 5, strict = TRUE))
These functions compute the Cholesky root elements of a covariance matrix and, conversely, build a covariance matrix from its Cholesky root elements.
cov_to_chol(cov, unique = TRUE) chol_to_cov(chol) unique_chol(chol)cov_to_chol(cov, unique = TRUE) chol_to_cov(chol) unique_chol(chol)
cov |
[ It can also be the zero matrix, in which case the Cholesky root is defined as the zero matrix. |
unique |
[ |
chol |
[ |
For cov_to_chol a numeric vector of Cholesky root
elements.
For chol_to_cov a covariance matrix.
Other matrix helpers:
check_correlation_matrix(),
check_covariance_matrix(),
check_one_hot_matrix(),
check_transition_probability_matrix(),
diff_cov(),
insert_matrix_column(),
matrix_diagonal_indices(),
matrix_indices(),
sample_correlation_matrix(),
sample_covariance_matrix(),
sample_transition_probability_matrix(),
stationary_distribution()
cov <- sample_covariance_matrix(4) chol <- cov_to_chol(cov) all.equal(cov, chol_to_cov(chol))cov <- sample_covariance_matrix(4) chol <- cov_to_chol(cov) all.equal(cov, chol_to_cov(chol))
The function ddirichlet() computes the density of a Dirichlet distribution.
The function rdirichlet() samples from a Dirichlet distribution.
The functions with suffix _cpp perform no input checks, hence are faster.
ddirichlet_cpp(x, concentration, log = FALSE) rdirichlet_cpp(concentration) ddirichlet(x, concentration, log = FALSE) rdirichlet(n = 1, concentration)ddirichlet_cpp(x, concentration, log = FALSE) rdirichlet_cpp(concentration) ddirichlet(x, concentration, log = FALSE) rdirichlet(n = 1, concentration)
x |
[ |
concentration |
[ |
log |
[ |
n |
[ |
For ddirichlet(): The density value.
For rdirichlet(): If n = 1 a vector of length p, else
a matrix of dimension n times p with samples as rows.
Other simulation helpers:
Simulator,
correlated_regressors(),
dmixnorm_cpp(),
dmvnorm_cpp(),
dtnorm_cpp(),
dwishart_cpp(),
gaussian_tv(),
simulate_markov_chain()
x <- c(0.5, 0.3, 0.2) concentration <- 1:3 # compute density ddirichlet(x = x, concentration = concentration) ddirichlet(x = x, concentration = concentration, log = TRUE) # sample rdirichlet(concentration = 1:3) rdirichlet(n = 4, concentration = 1:2)x <- c(0.5, 0.3, 0.2) concentration <- 1:3 # compute density ddirichlet(x = x, concentration = concentration) ddirichlet(x = x, concentration = concentration, log = TRUE) # sample rdirichlet(concentration = 1:3) rdirichlet(n = 4, concentration = 1:2)
data.frame columnsThis function deletes columns of a data.frame by name.
delete_columns_data.frame(df, column_names)delete_columns_data.frame(df, column_names)
df |
[ |
column_names |
[ |
The input df without the columns defined by column_names.
Other data.frame helpers:
group_data.frame(),
occurrence_info(),
round_data.frame()
df <- data.frame("label" = c("A", "B"), "number" = 1:10) delete_columns_data.frame(df = df, column_names = "label") delete_columns_data.frame(df = df, column_names = "number") delete_columns_data.frame(df = df, column_names = c("label", "number"))df <- data.frame("label" = c("A", "B"), "number" = 1:10) delete_columns_data.frame(df = df, column_names = "label") delete_columns_data.frame(df = df, column_names = "number") delete_columns_data.frame(df = df, column_names = c("label", "number"))
Provides a simple key-value interface based on R6.
keys[character()]
Available keys.
alias[list()]
Available keys per alias value.
new()
Initializing a new Dictionary object.
Dictionary$new( key_name, alias_name = NULL, value_names = character(), value_assert = alist(), allow_overwrite = TRUE, keys_reserved = character(), alias_choices = NULL, dictionary_name = NULL )
key_name[character(1)]
The name for the key variable.
alias_name[NULL | character(1)]
Optionally the name for the alias variable.
value_names[character(0)]
The names of the values connected to a key.
value_assert[alist(1)]
For each element in value_names, value_assert can have an
identically named element of the form checkmate::assert*(...), where
... can be any argument for the assertion function except for the
x argument.
allow_overwrite[logical(1)]
Allow overwriting existing keys with new values?
Duplicate keys are never allowed.
keys_reserved[character()]
Names that must not be used as keys.
alias_choices[NULL or character()]
Optionally possible values for the alias. Can also be NULL, then all
alias values are allowed.
dictionary_name[NULL or character()]
Optionally the name for the dictionary.
add()
Adding an element to the dictionary.
Dictionary$add(...)
...Values for
the key variable key_name (must be a single character),
the alias variable alias_name (optionally, must then be a
character vector),
all the variables specified for value_names (if any, they must
comply to the value_assert checks).
get()
Getting elements from the dictionary.
Dictionary$get(key, value = NULL)
key[character(1)]
A value for the key variable key_name. Use the $keys method for
available keys.
value[NULL | character(1)]
One of the elements in value_names, selecting the required value.
Can also be NULL (default) for all values connected to the
key, returned as a list.
remove()
Removing elements from the dictionary (and associated alias, if any).
Dictionary$remove(key)
key[character(1)]
A value for the key variable key_name. Use the $keys method for
available keys.
print()
Printing details of the dictionary.
Dictionary$print()
Other package helpers:
Storage,
check_missing(),
find_namespace_calls(),
find_pkg_functions(),
identical_structure(),
input_check_response(),
match_arg(),
package_logo(),
print_data.frame(),
print_matrix(),
system_information(),
unexpected_error(),
user_confirm()
# Managing variable metadata for a dataset meta_dict <- Dictionary$new( key_name = "var_name", alias_name = "category", value_names = c("label", "type"), value_assert = alist( label = checkmate::assert_string(), type = checkmate::assert_choice( choices = c("numeric", "factor", "character") ) ), allow_overwrite = FALSE, keys_reserved = c("id"), alias_choices = c("demographics", "outcome", "other"), dictionary_name = "Variable Metadata" ) # Add entries to the dictionary meta_dict$add( var_name = "age", label = "Age of respondent", type = "numeric", category = "demographics" ) meta_dict$add( var_name = "gender", label = "Gender identity", type = "factor", category = "demographics" ) meta_dict$add( var_name = "income", label = "Annual income in USD", type = "numeric", category = c("demographics", "outcome") ) # Print dictionary meta_dict$print() # Retrieve full metadata for a variable meta_dict$get("income") # Retrieve a specific piece of metadata meta_dict$get("income", value = "label") # Show variables by category meta_dict$alias# Managing variable metadata for a dataset meta_dict <- Dictionary$new( key_name = "var_name", alias_name = "category", value_names = c("label", "type"), value_assert = alist( label = checkmate::assert_string(), type = checkmate::assert_choice( choices = c("numeric", "factor", "character") ) ), allow_overwrite = FALSE, keys_reserved = c("id"), alias_choices = c("demographics", "outcome", "other"), dictionary_name = "Variable Metadata" ) # Add entries to the dictionary meta_dict$add( var_name = "age", label = "Age of respondent", type = "numeric", category = "demographics" ) meta_dict$add( var_name = "gender", label = "Gender identity", type = "factor", category = "demographics" ) meta_dict$add( var_name = "income", label = "Annual income in USD", type = "numeric", category = c("demographics", "outcome") ) # Print dictionary meta_dict$print() # Retrieve full metadata for a variable meta_dict$get("income") # Retrieve a specific piece of metadata meta_dict$get("income", value = "label") # Show variables by category meta_dict$alias
These functions difference and un-difference random vectors and covariance matrices.
diff_cov(cov, ref = 1) undiff_cov(cov_diff, ref = 1) delta(ref = 1, dim) M(ranking = seq_len(dim), dim)diff_cov(cov, ref = 1) undiff_cov(cov_diff, ref = 1) delta(ref = 1, dim) M(ranking = seq_len(dim), dim)
cov, cov_diff
|
[ |
ref |
[ |
dim |
[ |
ranking |
[ |
Assume is a multivariate normally distributed
random vector of dimension . We may want to consider the differenced
vector
excluding
the th element (hence, is of dimension
). Formally, , where
is a difference operator that depends on the reference
row . More precise, is the identity matrix of dimension
without row and with s in column .
The difference operator can be computed via
delta(ref = k, dim = n).
Then, , where
is the differenced covariance matrix with respect to row .
The differenced covariance matrix can be computed via
diff_delta(Sigma, ref = k).
Since is a non-bijective mapping, cannot be
uniquely restored from . However, it is possible to
compute a non-unique solution , such that
. For such a non-unique
solution, we add a column and a row of zeros
at column and row number to , respectively.
An "un-differenced" covariance matrix can be computed via
undiff_delta(Sigma_diff, ref = k).
As a alternative to , the function M() returns a matrix for
taking differences such that the resulting vector is negative.
A (differenced or un-differenced) covariance matrix.
Other matrix helpers:
check_correlation_matrix(),
check_covariance_matrix(),
check_one_hot_matrix(),
check_transition_probability_matrix(),
cov_to_chol(),
insert_matrix_column(),
matrix_diagonal_indices(),
matrix_indices(),
sample_correlation_matrix(),
sample_covariance_matrix(),
sample_transition_probability_matrix(),
stationary_distribution()
n <- 4 Sigma <- sample_covariance_matrix(dim = n) k <- 2 x <- c(1, 3, 2, 4) # build difference operator delta_k <- delta(ref = k, dim = n) # difference vector delta_k %*% x # difference Sigma (Sigma_diff <- diff_cov(Sigma, ref = k)) # un-difference Sigma (Sigma_0 <- undiff_cov(Sigma_diff, ref = k)) # difference again Sigma_diff_2 <- diff_cov(Sigma_0, ref = k) all.equal(Sigma_diff, Sigma_diff_2) # difference such that the resulting vector is negative M(ranking = order(x, decreasing = TRUE), dim = n) %*% xn <- 4 Sigma <- sample_covariance_matrix(dim = n) k <- 2 x <- c(1, 3, 2, 4) # build difference operator delta_k <- delta(ref = k, dim = n) # difference vector delta_k %*% x # difference Sigma (Sigma_diff <- diff_cov(Sigma, ref = k)) # un-difference Sigma (Sigma_0 <- undiff_cov(Sigma_diff, ref = k)) # difference again Sigma_diff_2 <- diff_cov(Sigma_0, ref = k) all.equal(Sigma_diff, Sigma_diff_2) # difference such that the resulting vector is negative M(ranking = order(x, decreasing = TRUE), dim = n) %*% x
The function dmixnorm() computes the density of a mixture of multivariate
normal distribution.
The function pmixnorm() computes the cumulative distribution function of a
mixture of multivariate normal distribution.
The function rmixnorm() samples from a mixture of multivariate normal
distribution.
The functions with suffix _cpp perform no input checks, hence are faster.
The univariate normal mixture is available as the special case p = 1.
dmixnorm_cpp(x, mean, Sigma, proportions) pmixnorm_cpp(x, mean, Sigma, proportions, abseps = 0.001) rmixnorm_cpp(mean, Sigma, proportions) dmixnorm(x, mean, Sigma, proportions) pmixnorm(x, mean, Sigma, proportions, abseps = 0.001) rmixnorm(n = 1, mean, Sigma, proportions)dmixnorm_cpp(x, mean, Sigma, proportions) pmixnorm_cpp(x, mean, Sigma, proportions, abseps = 0.001) rmixnorm_cpp(mean, Sigma, proportions) dmixnorm(x, mean, Sigma, proportions) pmixnorm(x, mean, Sigma, proportions, abseps = 0.001) rmixnorm(n = 1, mean, Sigma, proportions)
x |
[ |
mean |
[ |
Sigma |
[ |
proportions |
[ If proportions do not sum to unity, they are rescaled to do so. |
abseps |
[ |
n |
[ |
pmixnorm() is based on mvtnorm::pmvnorm with the randomized
Quasi-Monte-Carlo procedure by Genz and Bretz. The argument abseps controls
the accuracy of the Gaussian integral approximation.
For dmixnorm(): The density value.
For pmixnorm(): The value of the distribution function.
For rmixnorm(): If n = 1 a vector of length p (note
that it is a column vector for rmixnorm_cpp()), else
a matrix of dimension n times p with samples as rows.
Other simulation helpers:
Simulator,
correlated_regressors(),
ddirichlet_cpp(),
dmvnorm_cpp(),
dtnorm_cpp(),
dwishart_cpp(),
gaussian_tv(),
simulate_markov_chain()
x <- c(0, 0) mean <- matrix(c(-1, -1, 0, 0), ncol = 2) Sigma <- matrix(c(diag(2), diag(2)), ncol = 2) proportions <- c(0.7, 0.3) # compute density dmixnorm(x = x, mean = mean, Sigma = Sigma, proportions = proportions) # compute CDF pmixnorm(x = x, mean = mean, Sigma = Sigma, proportions = proportions) # sample rmixnorm(n = 3, mean = mean, Sigma = Sigma, proportions = proportions)x <- c(0, 0) mean <- matrix(c(-1, -1, 0, 0), ncol = 2) Sigma <- matrix(c(diag(2), diag(2)), ncol = 2) proportions <- c(0.7, 0.3) # compute density dmixnorm(x = x, mean = mean, Sigma = Sigma, proportions = proportions) # compute CDF pmixnorm(x = x, mean = mean, Sigma = Sigma, proportions = proportions) # sample rmixnorm(n = 3, mean = mean, Sigma = Sigma, proportions = proportions)
The function dmvnorm() computes the density of a multivariate normal
distribution.
The function pmvnorm() computes the cumulative distribution function of a
multivariate normal distribution.
The function rmvnorm() samples from a multivariate normal distribution.
The functions with suffix _cpp perform no input checks, hence are faster.
The univariate normal distribution is available as the special case p = 1.
dmvnorm_cpp(x, mean, Sigma, log = FALSE) pmvnorm_cpp(x, mean, Sigma, abseps = 0.001) rmvnorm_cpp(mean, Sigma, log = FALSE) dmvnorm(x, mean, Sigma, log = FALSE) pmvnorm(x, mean, Sigma, abseps = 0.001) rmvnorm(n = 1, mean, Sigma, log = FALSE)dmvnorm_cpp(x, mean, Sigma, log = FALSE) pmvnorm_cpp(x, mean, Sigma, abseps = 0.001) rmvnorm_cpp(mean, Sigma, log = FALSE) dmvnorm(x, mean, Sigma, log = FALSE) pmvnorm(x, mean, Sigma, abseps = 0.001) rmvnorm(n = 1, mean, Sigma, log = FALSE)
x |
[ |
mean |
[ For the functions without suffix |
Sigma |
[ For For the functions without suffix |
log |
[ |
abseps |
[ |
n |
[ |
pmvnorm() just calls mvtnorm::pmvnorm with the randomized
Quasi-Monte-Carlo procedure by Genz and Bretz. The argument abseps controls
the accuracy of the Gaussian integral approximation.
For dmvnorm(): The density value.
For pmvnorm(): The value of the distribution function.
For rmvnorm(): If n = 1 a vector of length p (note
that it is a column vector for rmvnorm_cpp()), else
a matrix of dimension n times p with samples as rows.
Other simulation helpers:
Simulator,
correlated_regressors(),
ddirichlet_cpp(),
dmixnorm_cpp(),
dtnorm_cpp(),
dwishart_cpp(),
gaussian_tv(),
simulate_markov_chain()
x <- c(0, 0) mean <- c(0, 0) Sigma <- diag(2) # compute density dmvnorm(x = x, mean = mean, Sigma = Sigma) dmvnorm(x = x, mean = mean, Sigma = Sigma, log = TRUE) # compute CDF pmvnorm(x = x, mean = mean, Sigma = Sigma) # sample rmvnorm(n = 3, mean = mean, Sigma = Sigma) rmvnorm(mean = mean, Sigma = Sigma, log = TRUE)x <- c(0, 0) mean <- c(0, 0) Sigma <- diag(2) # compute density dmvnorm(x = x, mean = mean, Sigma = Sigma) dmvnorm(x = x, mean = mean, Sigma = Sigma, log = TRUE) # compute CDF pmvnorm(x = x, mean = mean, Sigma = Sigma) # sample rmvnorm(n = 3, mean = mean, Sigma = Sigma) rmvnorm(mean = mean, Sigma = Sigma, log = TRUE)
This function measures the computation time of a call.
do.call_timed(what, args, units = "secs")do.call_timed(what, args, units = "secs")
what, args
|
Passed to |
units |
Passed to |
This function is a wrapper for do.call.
A list of the two elements "result" (the results of the do.call
call) and "time" (the computation time).
Other function helpers:
function_arguments(),
function_body(),
function_defaults(),
quiet(),
timed(),
try_silent(),
variable_name()
## Not run: what <- function(s) { Sys.sleep(s) return(s) } args <- list(s = 1) do.call_timed(what = what, args = args) ## End(Not run)## Not run: what <- function(s) { Sys.sleep(s) return(s) } args <- list(s = 1) do.call_timed(what = what, args = args) ## End(Not run)
The function dtnorm() computes the density of a truncated normal
distribution.
The function rtnorm() samples from a truncated normal distribution.
The function dttnorm() and rttnorm() compute the density and sample from
a two-sided truncated normal distribution, respectively.
The functions with suffix _cpp perform no input checks, hence are faster.
dtnorm_cpp(x, mean, sd, point, above, log = FALSE) dttnorm_cpp(x, mean, sd, lower, upper, log = FALSE) rtnorm_cpp(mean, sd, point, above, log = FALSE) rttnorm_cpp(mean, sd, lower, upper, log = FALSE) dtnorm(x, mean, sd, point, above, log = FALSE) dttnorm(x, mean, sd, lower, upper, log = FALSE) rtnorm(mean, sd, point, above, log = FALSE) rttnorm(mean, sd, lower, upper, log = FALSE)dtnorm_cpp(x, mean, sd, point, above, log = FALSE) dttnorm_cpp(x, mean, sd, lower, upper, log = FALSE) rtnorm_cpp(mean, sd, point, above, log = FALSE) rttnorm_cpp(mean, sd, lower, upper, log = FALSE) dtnorm(x, mean, sd, point, above, log = FALSE) dttnorm(x, mean, sd, lower, upper, log = FALSE) rtnorm(mean, sd, point, above, log = FALSE) rttnorm(mean, sd, lower, upper, log = FALSE)
x |
[ |
mean |
[ |
sd |
[ |
point, lower, upper
|
[ |
above |
[ |
log |
[ |
For dtnorm() and dttnorm(): The density value.
For rtnorm() and rttnorm(): The random draw
Other simulation helpers:
Simulator,
correlated_regressors(),
ddirichlet_cpp(),
dmixnorm_cpp(),
dmvnorm_cpp(),
dwishart_cpp(),
gaussian_tv(),
simulate_markov_chain()
x <- c(0, 0) mean <- c(0, 0) Sigma <- diag(2) # compute density dmvnorm(x = x, mean = mean, Sigma = Sigma) dmvnorm(x = x, mean = mean, Sigma = Sigma, log = TRUE) # sample rmvnorm(n = 3, mean = mean, Sigma = Sigma) rmvnorm(mean = mean, Sigma = Sigma, log = TRUE)x <- c(0, 0) mean <- c(0, 0) Sigma <- diag(2) # compute density dmvnorm(x = x, mean = mean, Sigma = Sigma) dmvnorm(x = x, mean = mean, Sigma = Sigma, log = TRUE) # sample rmvnorm(n = 3, mean = mean, Sigma = Sigma) rmvnorm(mean = mean, Sigma = Sigma, log = TRUE)
The function dwishart() computes the density of a Wishart distribution.
The function rwishart() samples from a Wishart distribution.
The functions with suffix _cpp perform no input checks, hence are faster.
dwishart_cpp(x, df, scale, log = FALSE, inv = FALSE) rwishart_cpp(df, scale, inv = FALSE) dwishart(x, df, scale, log = FALSE, inv = FALSE) rwishart(df, scale, inv = FALSE)dwishart_cpp(x, df, scale, log = FALSE, inv = FALSE) rwishart_cpp(df, scale, inv = FALSE) dwishart(x, df, scale, log = FALSE, inv = FALSE) rwishart(df, scale, inv = FALSE)
x |
[ |
df |
[ |
scale |
[ |
log |
[ |
inv |
[ |
For dwishart(): The density value.
For rwishart(): A matrix, the random draw.
Other simulation helpers:
Simulator,
correlated_regressors(),
ddirichlet_cpp(),
dmixnorm_cpp(),
dmvnorm_cpp(),
dtnorm_cpp(),
gaussian_tv(),
simulate_markov_chain()
x <- diag(2) df <- 6 scale <- matrix(c(1, -0.3, -0.3, 0.8), ncol = 2) # compute density dwishart(x = x, df = df, scale = scale) dwishart(x = x, df = df, scale = scale, log = TRUE) dwishart(x = x, df = df, scale = scale, inv = TRUE) # sample rwishart(df = df, scale = scale) rwishart(df = df, scale = scale, inv = TRUE) # expectation of Wishart is df * scale n <- 100 replicate(n, rwishart(df = df, scale = scale), simplify = FALSE) |> Reduce(f = "+") / n df * scale # expectation of inverse Wishart is scale / (df - p - 1) n <- 100 replicate(n, rwishart(df = df, scale = scale, TRUE), simplify = FALSE) |> Reduce(f = "+") / n scale / (df - 2 - 1)x <- diag(2) df <- 6 scale <- matrix(c(1, -0.3, -0.3, 0.8), ncol = 2) # compute density dwishart(x = x, df = df, scale = scale) dwishart(x = x, df = df, scale = scale, log = TRUE) dwishart(x = x, df = df, scale = scale, inv = TRUE) # sample rwishart(df = df, scale = scale) rwishart(df = df, scale = scale, inv = TRUE) # expectation of Wishart is df * scale n <- 100 replicate(n, rwishart(df = df, scale = scale), simplify = FALSE) |> Reduce(f = "+") / n df * scale # expectation of inverse Wishart is scale / (df - p - 1) n <- 100 replicate(n, rwishart(df = df, scale = scale, TRUE), simplify = FALSE) |> Reduce(f = "+") / n scale / (df - 2 - 1)
This function constructs the coordinates of vertices of a regular simplex
in and returns the first n of them,
scaled so that the pairwise Euclidean distance between any two vertices
equals dist,
and centered so their centroid is at center.
equidistant_vectors(dim, n = dim + 1, dist = 1, center = rep(0, dim))equidistant_vectors(dim, n = dim + 1, dist = 1, center = rep(0, dim))
dim |
[ |
n |
[ |
dist |
[ |
center |
[ |
A matrix, where each column is a vertex of the simplex.
Other vector helpers:
check_numeric_vector(),
check_probability_vector(),
chunk_vector(),
insert_vector_entry(),
map_indices(),
match_numerics(),
permutations(),
split_vector_at(),
subsets(),
vector_occurrence()
dim <- n <- 3 (dist <- runif(1)) (center <- rnorm(dim)) (V <- equidistant_vectors(dim = dim, n = n, dist = dist, center = center)) rowMeans(V) dist(t(V))dim <- n <- 3 (dist <- runif(1)) (center <- rnorm(dim)) (V <- equidistant_vectors(dim = dim, n = n, dist = dist, center = center)) rowMeans(V) dist(t(V))
This function searches for namespace calls in .R files, i.e., code lines of
the format <package name>::<function name>.
find_namespace_calls(path = "R", triple_colon = FALSE, as_list = FALSE)find_namespace_calls(path = "R", triple_colon = FALSE, as_list = FALSE)
path |
[ |
triple_colon |
[ |
as_list |
[ |
A data.frame. If as_list = TRUE, a list.
Other package helpers:
Dictionary,
Storage,
check_missing(),
find_pkg_functions(),
identical_structure(),
input_check_response(),
match_arg(),
package_logo(),
print_data.frame(),
print_matrix(),
system_information(),
unexpected_error(),
user_confirm()
## Not run: find_namespace_calls() find_namespace_calls(as_list = TRUE) ## End(Not run)## Not run: find_namespace_calls() find_namespace_calls(as_list = TRUE) ## End(Not run)
This function lists R functions found in an R package. It can inspect the
loaded namespace for exported and non-exported functions and, if a package
source path is available, scan .R files in R/.
find_pkg_functions(pkg, include_namespace = TRUE, include_source = TRUE)find_pkg_functions(pkg, include_namespace = TRUE, include_source = TRUE)
pkg |
[ |
include_namespace |
[ |
include_source |
[ |
include_namespace = TRUE inspects the package namespace with
asNamespace(). This works for installed packages and returns the R
functions that are actually available after the package is loaded, including
internal functions.
include_source = TRUE scans the package source files under R/. This is
useful when pkg points to a package source directory, for example while
developing a package before it is installed. If both options are TRUE, the
result is combined and duplicate function names are removed.
The title column is read from Rd documentation aliases. It is NA when no
matching Rd documentation entry is available for a function.
A tibble with one row per found R function and columns name,
title, exported, and signature.
Other package helpers:
Dictionary,
Storage,
check_missing(),
find_namespace_calls(),
identical_structure(),
input_check_response(),
match_arg(),
package_logo(),
print_data.frame(),
print_matrix(),
system_information(),
unexpected_error(),
user_confirm()
## Not run: find_pkg_functions("R6") find_pkg_functions(".") ## End(Not run)## Not run: find_pkg_functions("R6") find_pkg_functions(".") ## End(Not run)
This function returns the names of function arguments.
function_arguments(f, with_default = TRUE, with_ellipsis = TRUE)function_arguments(f, with_default = TRUE, with_ellipsis = TRUE)
f |
[ |
with_default |
[ |
with_ellipsis |
[ |
A character vector.
Other function helpers:
do.call_timed(),
function_body(),
function_defaults(),
quiet(),
timed(),
try_silent(),
variable_name()
f <- function(a, b = 1, c = "", ...) { } function_arguments(f) function_arguments(f, with_default = FALSE) function_arguments(f, with_ellipsis = FALSE)f <- function(a, b = 1, c = "", ...) { } function_arguments(f) function_arguments(f, with_default = FALSE) function_arguments(f, with_ellipsis = FALSE)
This function extracts the body of a function as a single character.
function_body(fun, braces = FALSE, nchar = getOption("width") - 4)function_body(fun, braces = FALSE, nchar = getOption("width") - 4)
fun |
[ |
braces |
[ |
nchar |
[ |
A character, the body of f.
Other function helpers:
do.call_timed(),
function_arguments(),
function_defaults(),
quiet(),
timed(),
try_silent(),
variable_name()
fun <- mean.default function_body(fun) function_body(fun, braces = TRUE) function_body(fun, nchar = 30)fun <- mean.default function_body(fun) function_body(fun, braces = TRUE) function_body(fun, nchar = 30)
This function returns the default function arguments (if any).
function_defaults(f, exclude = NULL)function_defaults(f, exclude = NULL)
f |
[ |
exclude |
[ Can be |
A named list.
Other function helpers:
do.call_timed(),
function_arguments(),
function_body(),
quiet(),
timed(),
try_silent(),
variable_name()
f <- function(a, b = 1, c = "", ...) { } function_defaults(f) function_defaults(f, exclude = "b")f <- function(a, b = 1, c = "", ...) { } function_defaults(f) function_defaults(f, exclude = "b")
Computes the total variation (TV) between two multivariate Gaussian
distributions :
The value ranges from 0 (identical distributions) to 1 (no overlap).
gaussian_tv( mean1, mean2, Sigma1, Sigma2, method = c("auto", "mc", "cubature"), n = 10000, tol_equal = 1e-06, eps = 1e-06 )gaussian_tv( mean1, mean2, Sigma1, Sigma2, method = c("auto", "mc", "cubature"), n = 10000, tol_equal = 1e-06, eps = 1e-06 )
mean1, mean2
|
[ |
Sigma1, Sigma2
|
[ |
method |
[
|
n |
[ |
tol_equal |
[ |
eps |
[ |
The total variation in [0, 1].
Other simulation helpers:
Simulator,
correlated_regressors(),
ddirichlet_cpp(),
dmixnorm_cpp(),
dmvnorm_cpp(),
dtnorm_cpp(),
dwishart_cpp(),
simulate_markov_chain()
### univariate case mean1 <- 0 mean2 <- 1 Sigma1 <- Sigma2 <- matrix(1) gaussian_tv(mean1, mean2, Sigma1, Sigma2) ### bivariate case mean1 <- c(0, 0) mean2 <- c(1, 1) Sigma1 <- matrix(c(1, 0.2, 0.2, 1), ncol = 2) Sigma2 <- matrix(c(1.5, -0.3, -0.3, 1), ncol = 2) gaussian_tv(mean1, mean2, Sigma1, Sigma2, method = "mc", n = 1e3)### univariate case mean1 <- 0 mean2 <- 1 Sigma1 <- Sigma2 <- matrix(1) gaussian_tv(mean1, mean2, Sigma1, Sigma2) ### bivariate case mean1 <- c(0, 0) mean2 <- c(1, 1) Sigma1 <- matrix(c(1, 0.2, 0.2, 1), ncol = 2) Sigma2 <- matrix(c(1.5, -0.3, -0.3, 1), ncol = 2) gaussian_tv(mean1, mean2, Sigma1, Sigma2, method = "mc", n = 1e3)
data.frame
This function groups a data.frame according to values of one column.
group_data.frame(df, by, keep_by = TRUE)group_data.frame(df, by, keep_by = TRUE)
df |
[ |
by |
[ |
keep_by |
[ |
A list of data.frames, subsets of df.
Other data.frame helpers:
delete_columns_data.frame(),
occurrence_info(),
round_data.frame()
df <- data.frame("label" = c("A", "B"), "number" = 1:10) group_data.frame(df = df, by = "label") group_data.frame(df = df, by = "label", keep_by = FALSE)df <- data.frame("label" = c("A", "B"), "number" = 1:10) group_data.frame(df = df, by = "label") group_data.frame(df = df, by = "label", keep_by = FALSE)
The Hermannslauf is an annual long-distance road and trail race in Germany that runs from Detmold to Bielefeld through the Teutoburg Forest. It is one of the best-known running events in the region and is especially noted for its demanding, hilly course of about 31 kilometers. This dataset contains historical information on editions of the race, including the date, temperature, and winning times for men and women.
From 1972 to 1976, the course followed the actual Hermannsweg for 30.4 kilometers, and in 1977 the first 13 kilometers were moved to a parallel route. Since 2005, the total course length has been 31.1 kilometers; until 2004, it was 30.6 kilometers. In 2020, the Hermannslauf was canceled due to the pandemic, and for the same reason, in 2021 it was exceptionally moved from April to October.
hermannhermann
A tibble with 54 rows and 8 columns:
the edition of the Hermannslauf
the year
the date
the temperature on that day at 12:00 noon; see details
the men's winner
the men's winner's total time in seconds
the women's winner
the women's winner's total time in seconds
Temperature in degrees Celsius, measured at 12:00 noon, obtained from different sources:
from 1973 to 1992 and from 1998 to 2013 from https://de.weatherspark.com/, Gütersloh Airport (approx. 30 km from start and finish)
from 1993 to 1997 from https://de.weatherspark.com/, Wunstorf Air Base (approx. 100 km from start and finish)
from 2014 to 2017 from https://de.weatherspark.com/, Hannover-Langenhagen Airport (approx. 90 km from start and finish)
from 2018 onward from https://meteostat.net/de/station/D7106, Airfield Bielefeld-Windelsbleiche (approx. 20 km from start and finish)
https://de.wikipedia.org/wiki/Hermannslauf
This function determines whether two objects have the same structure,
identical_structure(x, y)identical_structure(x, y)
x, y
|
[ |
Either TRUE if x and y have the same structure, and
FALSE, else.
Inspired by https://stackoverflow.com/a/45548885/15157768.
Other package helpers:
Dictionary,
Storage,
check_missing(),
find_namespace_calls(),
find_pkg_functions(),
input_check_response(),
match_arg(),
package_logo(),
print_data.frame(),
print_matrix(),
system_information(),
unexpected_error(),
user_confirm()
identical_structure(integer(1), 1L) identical_structure(diag(2), matrix(rnorm(4), 2, 2)) identical_structure(diag(2), data.frame(diag(2)))identical_structure(integer(1), 1L) identical_structure(diag(2), matrix(rnorm(4), 2, 2)) identical_structure(diag(2), data.frame(diag(2)))
This function provides a standardized response to input checks, ensuring consistency.
input_check_response( check, var_name = NULL, error = TRUE, prefix = "Input {.var {var_name}} is bad:" )input_check_response( check, var_name = NULL, error = TRUE, prefix = "Input {.var {var_name}} is bad:" )
check |
[ Can also be a |
var_name |
[ |
error |
[ |
prefix |
[ |
TRUE if check is TRUE (or any element in check is TRUE, if check
is a list) . Else, depending on error:
If error is TRUE, throws an error.
If error is FALSE, returns FALSE.
Other package helpers:
Dictionary,
Storage,
check_missing(),
find_namespace_calls(),
find_pkg_functions(),
identical_structure(),
match_arg(),
package_logo(),
print_data.frame(),
print_matrix(),
system_information(),
unexpected_error(),
user_confirm()
x <- "1" y <- 1 ### check is successful input_check_response( check = checkmate::check_character(x), var_name = "x", error = TRUE ) ### alternative checks input_check_response( check = list( checkmate::check_character(x), checkmate::check_character(y) ), var_name = "x", error = TRUE ) ### standardized check response ## Not run: input_check_response( check = checkmate::check_character(y), var_name = "y", error = TRUE ) input_check_response( check = list( checkmate::check_flag(x), checkmate::check_character(y) ), var_name = "y", error = TRUE ) ## End(Not run)x <- "1" y <- 1 ### check is successful input_check_response( check = checkmate::check_character(x), var_name = "x", error = TRUE ) ### alternative checks input_check_response( check = list( checkmate::check_character(x), checkmate::check_character(y) ), var_name = "x", error = TRUE ) ### standardized check response ## Not run: input_check_response( check = checkmate::check_character(y), var_name = "y", error = TRUE ) input_check_response( check = list( checkmate::check_flag(x), checkmate::check_character(y) ), var_name = "y", error = TRUE ) ## End(Not run)
This function inserts a column into a matrix.
insert_matrix_column(A, x, p)insert_matrix_column(A, x, p)
A |
[ |
x |
[ Can also be a single value. |
p |
[
|
A matrix.
Other matrix helpers:
check_correlation_matrix(),
check_covariance_matrix(),
check_one_hot_matrix(),
check_transition_probability_matrix(),
cov_to_chol(),
diff_cov(),
matrix_diagonal_indices(),
matrix_indices(),
sample_correlation_matrix(),
sample_covariance_matrix(),
sample_transition_probability_matrix(),
stationary_distribution()
A <- diag(3) x <- 1:3 insert_matrix_column(A, x, 0) insert_matrix_column(A, x, 1) insert_matrix_column(A, x, 2) insert_matrix_column(A, x, 3) ### also single value x <- 2 insert_matrix_column(A, x, 0) ### also multiple positions insert_matrix_column(A, x, 0:3) ### also trivial case insert_matrix_column(matrix(nrow = 0, ncol = 0), integer(), integer())A <- diag(3) x <- 1:3 insert_matrix_column(A, x, 0) insert_matrix_column(A, x, 1) insert_matrix_column(A, x, 2) insert_matrix_column(A, x, 3) ### also single value x <- 2 insert_matrix_column(A, x, 0) ### also multiple positions insert_matrix_column(A, x, 0:3) ### also trivial case insert_matrix_column(matrix(nrow = 0, ncol = 0), integer(), integer())
This function inserts a value into a vector.
insert_vector_entry(v, x, p)insert_vector_entry(v, x, p)
v |
[ |
x |
[ |
p |
[
|
A vector.
Other vector helpers:
check_numeric_vector(),
check_probability_vector(),
chunk_vector(),
equidistant_vectors(),
map_indices(),
match_numerics(),
permutations(),
split_vector_at(),
subsets(),
vector_occurrence()
v <- 1:3 x <- 0 insert_vector_entry(v, x, 0) insert_vector_entry(v, x, 1) insert_vector_entry(v, x, 2) insert_vector_entry(v, x, 3) ### also multiple positions insert_vector_entry(v, x, 0:3) ### also trivial case insert_vector_entry(integer(), integer(), integer())v <- 1:3 x <- 0 insert_vector_entry(v, x, 0) insert_vector_entry(v, x, 1) insert_vector_entry(v, x, 2) insert_vector_entry(v, x, 3) ### also multiple positions insert_vector_entry(v, x, 0:3) ### also trivial case insert_vector_entry(integer(), integer(), integer())
This function maps indices from an input vector to corresponding sequences of
grouped indices. Each element from the input specifies a group to be mapped
from the sequence, determined by the grouping size n.
map_indices(indices, n)map_indices(indices, n)
indices |
[ |
n |
[ |
This function is useful when working with indices arranged in fixed-size
groups, where each group can be referenced by a single index. For example, if
indices are structured in chunks of 3, calling this function with n = 3
will map the corresponding groups of 3 consecutive indices for the given
input indices, see the examples.
An integer vector, containing the mapped indices according to the
specified group size.
Other vector helpers:
check_numeric_vector(),
check_probability_vector(),
chunk_vector(),
equidistant_vectors(),
insert_vector_entry(),
match_numerics(),
permutations(),
split_vector_at(),
subsets(),
vector_occurrence()
# Example: Map indices based on groups of 3 map_indices(c(1, 3, 5), 3)# Example: Map indices based on groups of 3 map_indices(c(1, 3, 5), 3)
This function matches function arguments and is a modified version of
match.arg.
match_arg(arg, choices, several.ok = FALSE, none.ok = FALSE)match_arg(arg, choices, several.ok = FALSE, none.ok = FALSE)
arg |
[ |
choices |
[ |
several.ok |
[ |
none.ok |
[ |
The un-abbreviated version of the exact or unique partial match if there is
one. Otherwise, an error is signaled if several.ok is FALSE
or none.ok is FALSE.
When several.ok is TRUE and (at least) one element of
arg has a match, all un-abbreviated versions of matches are returned.
When none.ok is TRUE and arg has zero elements,
character(0) is returned.
Other package helpers:
Dictionary,
Storage,
check_missing(),
find_namespace_calls(),
find_pkg_functions(),
identical_structure(),
input_check_response(),
package_logo(),
print_data.frame(),
print_matrix(),
system_information(),
unexpected_error(),
user_confirm()
This function matches the indices of two numeric vectors as good as possible (that means with the smallest possible sum of deviations).
match_numerics(x, y)match_numerics(x, y)
x, y
|
[ |
An integer vector of length length(x) with the positions of
y in x.
Other vector helpers:
check_numeric_vector(),
check_probability_vector(),
chunk_vector(),
equidistant_vectors(),
insert_vector_entry(),
map_indices(),
permutations(),
split_vector_at(),
subsets(),
vector_occurrence()
x <- c(-1, 0, 1) y <- c(0.1, 1.5, -1.2) match_numerics(x, y)x <- c(-1, 0, 1) y <- c(0.1, 1.5, -1.2) match_numerics(x, y)
This function returns the indices of the diagonal elements of a quadratic matrix.
matrix_diagonal_indices(n, triangular = NULL)matrix_diagonal_indices(n, triangular = NULL)
n |
[ |
triangular |
[ |
An integer vector.
Other matrix helpers:
check_correlation_matrix(),
check_covariance_matrix(),
check_one_hot_matrix(),
check_transition_probability_matrix(),
cov_to_chol(),
diff_cov(),
insert_matrix_column(),
matrix_indices(),
sample_correlation_matrix(),
sample_covariance_matrix(),
sample_transition_probability_matrix(),
stationary_distribution()
# indices of diagonal elements n <- 3 matrix(1:n^2, n, n) matrix_diagonal_indices(n) # indices of diagonal elements of lower-triangular matrix L <- matrix(0, n, n) L[lower.tri(L, diag=TRUE)] <- 1:((n * (n + 1)) / 2) L matrix_diagonal_indices(n, triangular = "lower") # indices of diagonal elements of upper-triangular matrix U <- matrix(0, n, n) U[upper.tri(U, diag=TRUE)] <- 1:((n * (n + 1)) / 2) U matrix_diagonal_indices(n, triangular = "upper")# indices of diagonal elements n <- 3 matrix(1:n^2, n, n) matrix_diagonal_indices(n) # indices of diagonal elements of lower-triangular matrix L <- matrix(0, n, n) L[lower.tri(L, diag=TRUE)] <- 1:((n * (n + 1)) / 2) L matrix_diagonal_indices(n, triangular = "lower") # indices of diagonal elements of upper-triangular matrix U <- matrix(0, n, n) U[upper.tri(U, diag=TRUE)] <- 1:((n * (n + 1)) / 2) U matrix_diagonal_indices(n, triangular = "upper")
matrix indicesThis function returns matrix indices as character.
matrix_indices(x, prefix = "", exclude_diagonal = FALSE)matrix_indices(x, prefix = "", exclude_diagonal = FALSE)
x |
[ |
prefix |
[ |
exclude_diagonal |
[ |
A character vector.
Other matrix helpers:
check_correlation_matrix(),
check_covariance_matrix(),
check_one_hot_matrix(),
check_transition_probability_matrix(),
cov_to_chol(),
diff_cov(),
insert_matrix_column(),
matrix_diagonal_indices(),
sample_correlation_matrix(),
sample_covariance_matrix(),
sample_transition_probability_matrix(),
stationary_distribution()
M <- diag(3) matrix_indices(M) matrix_indices(M, "M_") matrix_indices(M, "M_", TRUE)M <- diag(3) matrix_indices(M) matrix_indices(M, "M_") matrix_indices(M, "M_", TRUE)
This function merges lists based on their element names. Elements are
only included in the final output list, if no former list has
contributed an element with the same name.
merge_lists(...)merge_lists(...)
... |
One or more named |
A list.
Other list helpers:
check_list_of_lists()
merge_lists(list("a" = 1, "b" = 2), list("b" = 3, "c" = 4, "d" = NULL))merge_lists(list("a" = 1, "b" = 2), list("b" = 3, "c" = 4, "d" = NULL))
This function provides verbose information about absolute or relative
element occurrences in data.frame columns.
occurrence_info(x, relative = FALSE, named = FALSE)occurrence_info(x, relative = FALSE, named = FALSE)
x |
[ |
relative |
[ |
named |
[ |
A character().
Other data.frame helpers:
delete_columns_data.frame(),
group_data.frame(),
round_data.frame()
occurrence_info(datasets::warpbreaks, relative = FALSE, named = TRUE)occurrence_info(datasets::warpbreaks, relative = FALSE, named = TRUE)
This function creates a basic R package logo. The logo has a white
background and the package name (with or without curly brackets) in the
center. The font size for the package name is scaled such that it fits inside
the logo. Type ?oeli to see an example.
package_logo( package_name, brackets = FALSE, background = ggplot2::ggplot() + ggplot2::theme_void(), s_x = 1, s_y = 1, s_width = 1, s_height = 1, white_around_sticker = FALSE )package_logo( package_name, brackets = FALSE, background = ggplot2::ggplot() + ggplot2::theme_void(), s_x = 1, s_y = 1, s_width = 1, s_height = 1, white_around_sticker = FALSE )
package_name |
[ |
brackets |
[ |
background |
A |
s_x, s_y, s_width, s_height, white_around_sticker
|
Passed on to |
A ggplot object.
Other package helpers:
Dictionary,
Storage,
check_missing(),
find_namespace_calls(),
find_pkg_functions(),
identical_structure(),
input_check_response(),
match_arg(),
print_data.frame(),
print_matrix(),
system_information(),
unexpected_error(),
user_confirm()
print(package_logo("my_package", brackets = TRUE))print(package_logo("my_package", brackets = TRUE))
This function creates all permutations of a given vector.
permutations(x)permutations(x)
x |
[ |
A list of all permutations of x.
Modified version of https://stackoverflow.com/a/20199902/15157768.
Other vector helpers:
check_numeric_vector(),
check_probability_vector(),
chunk_vector(),
equidistant_vectors(),
insert_vector_entry(),
map_indices(),
match_numerics(),
split_vector_at(),
subsets(),
vector_occurrence()
permutations(1:3) permutations(LETTERS[1:3])permutations(1:3) permutations(LETTERS[1:3])
data.frame
This function prints a (possibly abbreviated) data.frame.
print_data.frame( x, rows = NULL, cols = NULL, digits = NULL, row.names = TRUE, col.names = TRUE )print_data.frame( x, rows = NULL, cols = NULL, digits = NULL, row.names = TRUE, col.names = TRUE )
x |
[ |
rows, cols
|
[ Printing is abbreviated in the middle. Can be |
digits |
[ Negative values are allowed, resulting in rounding to a power of ten. Can be |
row.names, col.names
|
[ |
Invisibly returns x.
Other package helpers:
Dictionary,
Storage,
check_missing(),
find_namespace_calls(),
find_pkg_functions(),
identical_structure(),
input_check_response(),
match_arg(),
package_logo(),
print_matrix(),
system_information(),
unexpected_error(),
user_confirm()
x <- data.frame(1:10, LETTERS[1:10], stats::rnorm(10)) print_data.frame(x, rows = 7) print_data.frame(x, rows = 7, cols = 2) print_data.frame(x, rows = 7, cols = 2, digits = 1) print_data.frame(x, rows = 7, cols = 2, digits = 1, row.names = FALSE) print_data.frame(x, rows = 7, cols = 2, digits = 1, col.names = FALSE)x <- data.frame(1:10, LETTERS[1:10], stats::rnorm(10)) print_data.frame(x, rows = 7) print_data.frame(x, rows = 7, cols = 2) print_data.frame(x, rows = 7, cols = 2, digits = 1) print_data.frame(x, rows = 7, cols = 2, digits = 1, row.names = FALSE) print_data.frame(x, rows = 7, cols = 2, digits = 1, col.names = FALSE)
matrix
This function prints a (possibly abbreviated) matrix.
print_matrix( x, rowdots = 4, coldots = 4, digits = 2, label = NULL, simplify = FALSE, details = !simplify )print_matrix( x, rowdots = 4, coldots = 4, digits = 2, label = NULL, simplify = FALSE, details = !simplify )
x |
[ |
rowdots |
[ |
coldots |
[ |
digits |
[ |
label |
[ |
simplify |
[ |
details |
[ |
Invisibly returns x.
This function is a modified version of pprint() from the {ramify}
package.
Other package helpers:
Dictionary,
Storage,
check_missing(),
find_namespace_calls(),
find_pkg_functions(),
identical_structure(),
input_check_response(),
match_arg(),
package_logo(),
print_data.frame(),
system_information(),
unexpected_error(),
user_confirm()
print_matrix(x = 1, label = "single numeric") print_matrix(x = LETTERS[1:26], label = "letters") print_matrix(x = 1:3, coldots = 2) print_matrix(x = matrix(rnorm(99), ncol = 1), label = "single column matrix") print_matrix(x = matrix(1:100, nrow = 1), label = "single row matrix") print_matrix(x = matrix(LETTERS[1:24], ncol = 6), label = "big matrix") print_matrix(x = diag(5), coldots = 2, rowdots = 2, simplify = TRUE)print_matrix(x = 1, label = "single numeric") print_matrix(x = LETTERS[1:26], label = "letters") print_matrix(x = 1:3, coldots = 2) print_matrix(x = matrix(rnorm(99), ncol = 1), label = "single column matrix") print_matrix(x = matrix(1:100, nrow = 1), label = "single row matrix") print_matrix(x = matrix(LETTERS[1:24], ncol = 6), label = "big matrix") print_matrix(x = diag(5), coldots = 2, rowdots = 2, simplify = TRUE)
This function silences warnings, messages and any cat() or print()
output from R expressions or functions.
quiet(x, print_cat = TRUE, message = TRUE, warning = TRUE)quiet(x, print_cat = TRUE, message = TRUE, warning = TRUE)
x |
[ |
print_cat |
[ |
message |
[ |
warning |
[ |
Invisibly the expression x.
This function is a modified version of quiet.
Other function helpers:
do.call_timed(),
function_arguments(),
function_body(),
function_defaults(),
timed(),
try_silent(),
variable_name()
f <- function() { warning("warning") message("message") cat("cat") print("print") } quiet(f())f <- function() { warning("warning") message("message") cat("cat") print("print") } quiet(f())
numeric columns of a data.frame
This function rounds (only) the numeric columns of a
data.frame.
round_data.frame(df, digits = 0)round_data.frame(df, digits = 0)
df |
[ |
digits |
[ Negative values are allowed, resulting in rounding to a power of ten. Can be |
A data.frame.
Other data.frame helpers:
delete_columns_data.frame(),
group_data.frame(),
occurrence_info()
df <- data.frame("label" = c("A", "B"), "number" = rnorm(10)) round_data.frame(df, digits = 1)df <- data.frame("label" = c("A", "B"), "number" = rnorm(10)) round_data.frame(df, digits = 1)
This function samples a correlation matrix by sampling a covariance matrix from an inverse Wishart distribution and transforming it to a correlation matrix.
sample_correlation_matrix(dim, df = dim, scale = diag(dim))sample_correlation_matrix(dim, df = dim, scale = diag(dim))
dim |
[ |
df |
[ |
scale |
[ |
A correlation matrix.
Other matrix helpers:
check_correlation_matrix(),
check_covariance_matrix(),
check_one_hot_matrix(),
check_transition_probability_matrix(),
cov_to_chol(),
diff_cov(),
insert_matrix_column(),
matrix_diagonal_indices(),
matrix_indices(),
sample_covariance_matrix(),
sample_transition_probability_matrix(),
stationary_distribution()
sample_correlation_matrix(dim = 3)sample_correlation_matrix(dim = 3)
This function samples a covariance matrix from an inverse Wishart distribution.
sample_covariance_matrix(dim, df = dim, scale = diag(dim), diag = FALSE)sample_covariance_matrix(dim, df = dim, scale = diag(dim), diag = FALSE)
dim |
[ |
df |
[ |
scale |
[ |
diag |
[ |
A covariance matrix.
Other matrix helpers:
check_correlation_matrix(),
check_covariance_matrix(),
check_one_hot_matrix(),
check_transition_probability_matrix(),
cov_to_chol(),
diff_cov(),
insert_matrix_column(),
matrix_diagonal_indices(),
matrix_indices(),
sample_correlation_matrix(),
sample_transition_probability_matrix(),
stationary_distribution()
sample_covariance_matrix(dim = 3)sample_covariance_matrix(dim = 3)
This function returns a random, squared matrix of dimension dim
that fulfills the properties of a transition probability matrix.
sample_transition_probability_matrix(dim, state_persistent = TRUE)sample_transition_probability_matrix(dim, state_persistent = TRUE)
dim |
[ |
state_persistent |
[ |
A transition probability matrix.
Other matrix helpers:
check_correlation_matrix(),
check_covariance_matrix(),
check_one_hot_matrix(),
check_transition_probability_matrix(),
cov_to_chol(),
diff_cov(),
insert_matrix_column(),
matrix_diagonal_indices(),
matrix_indices(),
sample_correlation_matrix(),
sample_covariance_matrix(),
stationary_distribution()
sample_transition_probability_matrix(dim = 3)sample_transition_probability_matrix(dim = 3)
This function simulates a Markov chain.
simulate_markov_chain(Gamma, T, delta = oeli::stationary_distribution(Gamma))simulate_markov_chain(Gamma, T, delta = oeli::stationary_distribution(Gamma))
Gamma |
[ |
T |
[ |
delta |
[ The stationary distribution is used by default. |
A numeric vector of length T with states.
Other simulation helpers:
Simulator,
correlated_regressors(),
ddirichlet_cpp(),
dmixnorm_cpp(),
dmvnorm_cpp(),
dtnorm_cpp(),
dwishart_cpp(),
gaussian_tv()
Gamma <- matrix(c(0.8, 0.2, 0.3, 0.7), byrow = TRUE, nrow = 2) delta <- c(0.6, 0.4) simulate_markov_chain(Gamma = Gamma, T = 20, delta = delta)Gamma <- matrix(c(0.8, 0.2, 0.3, 0.7), byrow = TRUE, nrow = 2) delta <- c(0.6, 0.4) simulate_markov_chain(Gamma = Gamma, T = 20, delta = delta)
Creates a simulation setup, where a function f is evaluated runs times,
optionally at each combination of input values.
Provides some convenience (see below for more details):
Simulation results can be restored from a backup if the R session crashes.
More simulation runs can be conducted after the initial simulation, failed simulation cases can be re-run.
Parallel computation and progress updates are supported.
Simulation results can be saved to disk, allowing you to restore the results
if the R session is interrupted or crashes before the simulation completes.
To enable backup, set backup = TRUE in the $go() method, which will
create a backup directory at the location specified by path.
To restore, use Simulator$initialize(use_backup = path).
If additional simulation runs are needed, simply call the $go() method
again. Any cases that were not successfully completed in previous runs will
be attempted again.
By default, simulations run sequentially. But since they are independent,
they can be parallelized to decrease computation time. To enable parallel
computation, use the {future} framework.
For example, run
future::plan(future::multisession, workers = 4)
in advance for computation in 4 parallel R sessions.
Use the {progressr} framework to
get progress updates. For example, run the following in advance:
progressr::handlers(global = TRUE) progressr::handlers( progressr::handler_progress(format = ">> :percent, :eta to go :message") )
results[tibble, read-only]
The simulation results.
cases[tibble, read-only]
The simulation cases.
new()
Initialize a Simulator object, either a new one or from backup.
Simulator$new(
use_backup = NULL,
verbose = getOption("verbose", default = FALSE)
)use_backup[NULL | character(1)]
Optionally a path to a backup folder previously used in $go().
verbose[logical(1)]
Provide info? Does not include progress updates. For that, see details.
print()
Print method.
Simulator$print()
define()
Define function and arguments for a new Simulator object.
Simulator$define(f, ...)
f[function]
A function to evaluate.
...Arguments for f. Each value must be
named after an argument of f, and
a list, where each element is a variant of that argument for f.
go()
Run simulations.
Simulator$go(
runs = 0,
backup = FALSE,
path = paste0("backup_", format(Sys.time(), "%Y-%m-%d-%H-%M-%S"))
)runs[integer(1)]
The number of (additional) simulation runs.
If runs = 0, only pending cases (if any) are solved.
backup[logical(1)]
Create a backup under path?
path[character(1)]
Only relevant, if backup = TRUE.
In this case, a path for a new folder, which does not yet exist and allows reading and writing.
Other simulation helpers:
correlated_regressors(),
ddirichlet_cpp(),
dmixnorm_cpp(),
dmvnorm_cpp(),
dtnorm_cpp(),
dwishart_cpp(),
gaussian_tv(),
simulate_markov_chain()
# 1. Initialize a new simulation setup: object <- Simulator$new(verbose = TRUE) # 2. Define function `f` and arguments (if any): f <- function(x, y = 1) { Sys.sleep(runif(1)) # to see progress updates x + y } x_args <- list(1, 2) object$define(f = f, x = x_args) print(object) # 3. Define 'future' and 'progress' (optional): ## Not run: future::plan(future::sequential) progressr::handlers(global = TRUE) ## End(Not run) # 4. Evaluate `f` `runs` times at each parameter combination: path <- file.path( tempdir(), paste0("backup_", format(Sys.time(), "%Y-%m-%d-%H-%M-%S")) ) object$go(runs = 2, backup = TRUE, path = path) # 5. Access the results: object$results # 6. Check if cases are pending or if an error occurred: object$cases # 7. Restore simulation results from backup: object_restored <- Simulator$new(use_backup = path) print(object_restored) ## Not run: all.equal(object, object_restored) # 8. Run more simulations and pending simulations (if any): object_restored$go(runs = 2)# 1. Initialize a new simulation setup: object <- Simulator$new(verbose = TRUE) # 2. Define function `f` and arguments (if any): f <- function(x, y = 1) { Sys.sleep(runif(1)) # to see progress updates x + y } x_args <- list(1, 2) object$define(f = f, x = x_args) print(object) # 3. Define 'future' and 'progress' (optional): ## Not run: future::plan(future::sequential) progressr::handlers(global = TRUE) ## End(Not run) # 4. Evaluate `f` `runs` times at each parameter combination: path <- file.path( tempdir(), paste0("backup_", format(Sys.time(), "%Y-%m-%d-%H-%M-%S")) ) object$go(runs = 2, backup = TRUE, path = path) # 5. Access the results: object$results # 6. Check if cases are pending or if an error occurred: object$cases # 7. Restore simulation results from backup: object_restored <- Simulator$new(use_backup = path) print(object_restored) ## Not run: all.equal(object, object_restored) # 8. Run more simulations and pending simulations (if any): object_restored$go(runs = 2)
This function splits a vector at specific positions.
split_vector_at(x, at)split_vector_at(x, at)
x |
[atomic()'] |
at |
[ For example, |
A list.
Based on https://stackoverflow.com/a/19274414.
Other vector helpers:
check_numeric_vector(),
check_probability_vector(),
chunk_vector(),
equidistant_vectors(),
insert_vector_entry(),
map_indices(),
match_numerics(),
permutations(),
subsets(),
vector_occurrence()
x <- 1:10 split_vector_at(x, c(2, 3, 5, 7))x <- 1:10 split_vector_at(x, c(2, 3, 5, 7))
This function computes the stationary distribution corresponding to a transition probability matrix.
stationary_distribution(tpm, soft_fail = FALSE)stationary_distribution(tpm, soft_fail = FALSE)
tpm |
[ |
soft_fail |
[ |
A numeric vector.
Other matrix helpers:
check_correlation_matrix(),
check_covariance_matrix(),
check_one_hot_matrix(),
check_transition_probability_matrix(),
cov_to_chol(),
diff_cov(),
insert_matrix_column(),
matrix_diagonal_indices(),
matrix_indices(),
sample_correlation_matrix(),
sample_covariance_matrix(),
sample_transition_probability_matrix()
tpm <- matrix(0.05, nrow = 3, ncol = 3) diag(tpm) <- 0.9 stationary_distribution(tpm)tpm <- matrix(0.05, nrow = 3, ncol = 3) diag(tpm) <- 0.9 stationary_distribution(tpm)
Provides a simple indexing interface for list elements based on R6. Basically, it allows to store items in a list and to regain them based on identifiers defined by the user.
The output depends on the method:
$new() returns a Storage object.
$add(), $remove(), and $print() invisibly return the
Storage object (to allow for method chaining)
$get() returns the requested element(s)
$number() returns an integer
$indices() return an integer vector
An identifier is a character, typically a binary property. Identifiers
can be negated by placing an exclamation mark ("!") in front of them.
Identifiers that have been assigned to other elements previously do not need
to be specified again for new elements; instead, a default value can be used.
This default value can be defined either globally for all cases (via the
$missing_identifier field) or separately for each specific case (via
the method argument).
If desired, the user can be asked for confirmation when adding, extracting,
or removing elements using identifiers. This behavior can be set globally
through the $confirm field or customized separately for each specific
case via the method argument.
identifier[character()]
The identifiers used.
confirm[logical(1)]
The default value for confirmations.
missing_identifier[logical(1)]
The default value for not specified identifiers.
hide_warnings[logical(1)]
Hide warnings (for example if unknown identifiers are selected)?
new()
Initializing a Storage object.
Storage$new()
add()
Adding an element.
Storage$add( x, identifier, confirm = interactive() & self$confirm, missing_identifier = self$missing_identifier )
x[any]
An object to be saved.
identifier[character()]
Pne or more identifiers (the identifier "all" is reserved to select
all elements).
confirm[logical(1)]
Prompted for confirmation?
missing_identifier[logical(1) | NA]
The value for not specified identifiers.
get()
Getting elements.
Storage$get( identifier = character(), ids = integer(), logical = "and", confirm = interactive() & self$confirm, missing_identifier = self$missing_identifier, id_names = FALSE )
identifier[character()]
Pne or more identifiers (the identifier "all" is reserved to select
all elements).
ids[integer()]
One or more ids.
logical[character(1)]
In the case that multiple identifiers are selected, how should they be
combined? Options are:
"and" (the default): the identifiers are combined with logical and
(all identifiers must be TRUE)
"or": the identifiers are combined with logical or (at least one
identifier must be TRUE)
confirm[logical(1)]
Prompted for confirmation?
missing_identifier[logical(1) | NA]
The value for not specified identifiers.
id_names[logical(1)]
Name the elements according to their ids?
remove()
removing elements
Storage$remove( identifier = character(), ids = integer(), logical = "and", confirm = interactive() & self$confirm, missing_identifier = self$missing_identifier, shift_ids = TRUE )
identifier[character()]
Pne or more identifiers (the identifier "all" is reserved to select
all elements).
ids[integer()]
One or more ids.
logical[character(1)]
In the case that multiple identifiers are selected, how should they be
combined? Options are:
"and" (the default): the identifiers are combined with logical and
(all identifiers must be TRUE)
"or": the identifiers are combined with logical or (at least one
identifier must be TRUE)
confirm[logical(1)]
Prompted for confirmation?
missing_identifier[logical(1) | NA]
The value for not specified identifiers.
shift_ids[logical(1)]
Shift ids when in-between elements are removed?
number()
Computing the number of identified elements.
Storage$number( identifier = "all", missing_identifier = self$missing_identifier, logical = "and", confirm = FALSE )
identifier[character()]
Pne or more identifiers (the identifier "all" is reserved to select
all elements).
missing_identifier[logical(1) | NA]
The value for not specified identifiers.
logical[character(1)]
In the case that multiple identifiers are selected, how should they be
combined? Options are:
"and" (the default): the identifiers are combined with logical and
(all identifiers must be TRUE)
"or": the identifiers are combined with logical or (at least one
identifier must be TRUE)
confirm[logical(1)]
Prompted for confirmation?
indices()
Returning indices based on defined identifiers.
Storage$indices( identifier = "all", logical = "and", confirm = interactive() & self$confirm )
identifier[character()]
Pne or more identifiers (the identifier "all" is reserved to select
all elements).
logical[character(1)]
In the case that multiple identifiers are selected, how should they be
combined? Options are:
"and" (the default): the identifiers are combined with logical and
(all identifiers must be TRUE)
"or": the identifiers are combined with logical or (at least one
identifier must be TRUE)
confirm[logical(1)]
Prompted for confirmation?
print()
Printing details of the saved elements.
Storage$print(...)
...Currently not used.
Other package helpers:
Dictionary,
check_missing(),
find_namespace_calls(),
find_pkg_functions(),
identical_structure(),
input_check_response(),
match_arg(),
package_logo(),
print_data.frame(),
print_matrix(),
system_information(),
unexpected_error(),
user_confirm()
### 1. Create a `Storage` object: my_storage <- Storage$new() # 2. Add elements along with identifiers: my_storage$ add(42, c("number", "rational"))$ add(pi, c("number", "!rational"))$ add("fear of black cats", c("text", "!rational"))$ add("wearing a seat belt", c("text", "rational"))$ add(mean, "function") # 3. What elements are stored? print(my_storage) # 4. Extract elements based on identifiers: my_storage$get("rational") my_storage$get("!rational") my_storage$get(c("text", "!rational")) my_storage$get("all") # get all elements my_storage$get(c("text", "!text")) my_storage$get(c("text", "!text"), logical = "or") # 5. Extract elements based on ids: my_storage$get(ids = 4:5) my_storage$get(ids = 4:5, id_names = TRUE) # add the ids as names### 1. Create a `Storage` object: my_storage <- Storage$new() # 2. Add elements along with identifiers: my_storage$ add(42, c("number", "rational"))$ add(pi, c("number", "!rational"))$ add("fear of black cats", c("text", "!rational"))$ add("wearing a seat belt", c("text", "rational"))$ add(mean, "function") # 3. What elements are stored? print(my_storage) # 4. Extract elements based on identifiers: my_storage$get("rational") my_storage$get("!rational") my_storage$get(c("text", "!rational")) my_storage$get("all") # get all elements my_storage$get(c("text", "!text")) my_storage$get(c("text", "!text"), logical = "or") # 5. Extract elements based on ids: my_storage$get(ids = 4:5) my_storage$get(ids = 4:5, id_names = TRUE) # add the ids as names
This function generates subsets of a vector.
subsets(v, n = seq_along(v))subsets(v, n = seq_along(v))
v |
[atomic()'] |
n |
[integer(1)'] |
A list, each element is a subset of v.
Other vector helpers:
check_numeric_vector(),
check_probability_vector(),
chunk_vector(),
equidistant_vectors(),
insert_vector_entry(),
map_indices(),
match_numerics(),
permutations(),
split_vector_at(),
vector_occurrence()
v <- 1:3 subsets(v) subsets(v, c(1, 3)) # only subsets of length 1 or 3 subsets(integer()) # trivial case worksv <- 1:3 subsets(v) subsets(v, c(1, 3)) # only subsets of length 1 or 3 subsets(integer()) # trivial case works
This function returns a list of general system level information.
system_information()system_information()
A list with elements:
maschine, the model name of the device
cores, the number of cores
ram, the size of the RAM
os, the operating system
rversion, the R version used
Other package helpers:
Dictionary,
Storage,
check_missing(),
find_namespace_calls(),
find_pkg_functions(),
identical_structure(),
input_check_response(),
match_arg(),
package_logo(),
print_data.frame(),
print_matrix(),
unexpected_error(),
user_confirm()
system_information()system_information()
This function interrupts an evaluation after a certain number of seconds.
Note the limitations documented in setTimeLimit.
timed(expression, seconds = Inf, on_time_out = "silent")timed(expression, seconds = Inf, on_time_out = "silent")
expression |
[ |
seconds |
[ |
on_time_out |
[
|
The value of expression or, if the evaluation time exceeded, whatever
is specified for on_time_out.
Other function helpers:
do.call_timed(),
function_arguments(),
function_body(),
function_defaults(),
quiet(),
try_silent(),
variable_name()
foo <- function(x) { for (i in 1:10) Sys.sleep(x / 10) return(x) } timed(foo(0.5), 1) timed(foo(1.5), 1)foo <- function(x) { for (i in 1:10) Sys.sleep(x / 10) return(x) } timed(foo(0.5), 1) timed(foo(1.5), 1)
This function tries to execute expr and returns a string with the
error message if the execution failed.
try_silent(expr)try_silent(expr)
expr |
[ |
This function is a wrapper for try.
Either the value of expr or in case of a failure an object of class
fail, which contains the error message.
Other function helpers:
do.call_timed(),
function_arguments(),
function_body(),
function_defaults(),
quiet(),
timed(),
variable_name()
## Not run: try_silent(1 + 1) try_silent(1 + "1") ## End(Not run)## Not run: try_silent(1 + 1) try_silent(1 + "1") ## End(Not run)
This function reacts to an unexpected error by throwing an error and linking to an issue site with the request to submit an issue.
unexpected_error( msg = "Oops, an unexpected error occurred.", issue_link = "https://github.com/loelschlaeger/oeli/issues" )unexpected_error( msg = "Oops, an unexpected error occurred.", issue_link = "https://github.com/loelschlaeger/oeli/issues" )
msg |
[ |
issue_link |
[ |
No return value, but it throws an error.
Other package helpers:
Dictionary,
Storage,
check_missing(),
find_namespace_calls(),
find_pkg_functions(),
identical_structure(),
input_check_response(),
match_arg(),
package_logo(),
print_data.frame(),
print_matrix(),
system_information(),
user_confirm()
This function asks in an interactive question a binary question.
user_confirm(question = "Question?", default = FALSE)user_confirm(question = "Question?", default = FALSE)
question |
[ |
default |
[ |
Either TRUE or FALSE.
Other package helpers:
Dictionary,
Storage,
check_missing(),
find_namespace_calls(),
find_pkg_functions(),
identical_structure(),
input_check_response(),
match_arg(),
package_logo(),
print_data.frame(),
print_matrix(),
system_information(),
unexpected_error()
This function tries to determine the name of a variable passed to a
function.
variable_name(variable, fallback = "unnamed")variable_name(variable, fallback = "unnamed")
variable |
[ |
fallback |
[ |
A character, the variable name.
Other function helpers:
do.call_timed(),
function_arguments(),
function_body(),
function_defaults(),
quiet(),
timed(),
try_silent()
variable_name(a) f <- function(x) variable_name(x) f(x = a)variable_name(a) f <- function(x) variable_name(x) f(x = a)
This function finds the positions of first or last occurrence of unique vector elements.
vector_occurrence(x, type = "first")vector_occurrence(x, type = "first")
x |
[ |
type |
[ |
An integer vector, the positions of the unique vector elements.
The ordering corresponds to unique(x), i.e., the -th element in
the output is the (first or last) occurrence of the -th element from
unique(x).
Other vector helpers:
check_numeric_vector(),
check_probability_vector(),
chunk_vector(),
equidistant_vectors(),
insert_vector_entry(),
map_indices(),
match_numerics(),
permutations(),
split_vector_at(),
subsets()
x <- c(1, 1, 1, 2, 2, 2, 3, 3, 3) unique(x) vector_occurrence(x, "first") vector_occurrence(x, "last")x <- c(1, 1, 1, 2, 2, 2, 3, 3, 3) unique(x) vector_occurrence(x, "first") vector_occurrence(x, "last")