| Title: | Miscellaneous Helper Functions for B. Bischl |
| Version: | 1.13.1 |
| Description: | Miscellaneous helper functions for and from B. Bischl and some other guys, mainly for package development. |
| License: | BSD_2_clause + file LICENSE |
| URL: | https://github.com/berndbischl/BBmisc |
| BugReports: | https://github.com/berndbischl/BBmisc/issues |
| Imports: | checkmate (≥ 1.8.0), data.table, methods, stats, utils |
| Suggests: | codetools, microbenchmark, testthat |
| ByteCompile: | yes |
| Encoding: | UTF-8 |
| RoxygenNote: | 7.3.3 |
| NeedsCompilation: | yes |
| Packaged: | 2026-01-21 10:42:03 UTC; marc |
| Author: | Bernd Bischl [aut, cre], Michel Lang [aut], Jakob Bossek [aut], Daniel Horn [aut], Jakob Richter [aut], Dirk Surmann [aut] |
| Maintainer: | Bernd Bischl <bernd_bischl@gmx.net> |
| Repository: | CRAN |
| Date/Publication: | 2026-01-21 11:20:02 UTC |
Check if some values are covered by the range of the values in a second vector
Description
Tests whether values in x are between the minimum and maximum of y.
Usage
x %btwn% y
Arguments
x |
[ |
y |
[ |
Value
[logical(n)]. For each value in x: Is it in the range of y?
Examples
x = 3
y = c(-1,2,5)
x %btwn% y
Simply a negated in operator
Description
Tests if elements of x are not in y.
Usage
x %nin% y
Arguments
x |
[ |
y |
[ |
A wrapper to add to the class attribute
Description
Adds classes to the class attribute of an object.
Usage
addClasses(x, classes)
Arguments
x |
[any] |
classes |
[ |
Value
Changed object x.
Examples
x = list()
print(class(x))
x = addClasses(x, c("foo1", "foo2"))
print(class(x))
Parses ... arguments to a named list
Description
The deparsed name will be used for arguments with missing names.
Missing names will be set to NA.
Usage
argsAsNamedList(...)
Arguments
... |
Arbitrary number of objects. |
Value
[list]: Named list with objects.
Examples
z = 3
argsAsNamedList(x = 1, y = 2, z)
Extracts a named element from a list of lists
Description
Converts a list of vectors into a matrix with vectors as columns or rows.
Usage
asMatrixCols(xs, row.names, col.names)
asMatrixRows(xs, row.names, col.names)
Arguments
xs |
[ |
row.names |
[ |
col.names |
[ |
Value
[matrix].
Converts a string into a quoted expression
Description
Works the same as if you would have entered the expression and called
quote on it.
Usage
asQuoted(s, env = parent.frame())
Arguments
s |
[ |
env |
[ |
Value
Quoted expression.
Examples
asQuoted("x == 3")
Simple bin packing
Description
Maps numeric items in x into groups with sum
less or equal than capacity.
A very simple greedy algorithm is used, which is not really optimized
for speed. This is a convenience function for smaller vectors, not
a competetive solver for the real binbacking problem.
If an element of x exceeds capacity, an error
is thrown.
Usage
binPack(x, capacity)
Arguments
x |
[ |
capacity |
[ |
Value
[integer]. Integer with values “1” to “n.bins”
indicating bin membership.
Examples
x = 1:10
bp = binPack(x, 11)
xs = split(x, bp)
print(xs)
print(sapply(xs, sum))
Combine multiple factors and return a factor
Description
Note that function does not inherit from c to not change R semantics behind your back when this
package is loaded.
Usage
cFactor(...)
Arguments
... |
[ |
Value
[factor].
Examples
f1 = factor(c("a", "b"))
f2 = factor(c("b", "c"))
print(c(f1, f2))
print(cFactor(f1, f2))
Capitalize strings in a vector
Description
Capitalise first word or all words of a character vector. Lower back of vector element or word, respectively.
Usage
capitalizeStrings(x, all.words = FALSE, lower.back = FALSE)
Arguments
x |
[ |
all.words |
[ |
lower.back |
[ |
Value
Capitalized vector: [character(n)].
Examples
capitalizeStrings(c("the taIl", "wags The dOg", "That looks fuNny!"))
capitalizeStrings(c("the taIl", "wags The dOg", "That looks fuNny!")
, all.words = TRUE, lower.back = TRUE)
Wrapper for cat and sprintf
Description
A simple wrapper for cat(sprintf(...)).
Usage
catf(..., file = "", append = FALSE, newline = TRUE)
Arguments
... |
[any] |
file |
[ |
append |
[ |
newline |
[ |
Value
Nothing.
Examples
msg = "a message."
catf("This is %s", msg)
Check for a function argument
Description
Throws exception if checks are not passed. Note that argument is evaluated when checked.
This function is superseded by the package checkmate and might get deprecated in the future. Please
Usage
checkArg(
x,
cl,
s4 = FALSE,
len,
min.len,
max.len,
choices,
subset,
lower = NA,
upper = NA,
na.ok = TRUE,
formals
)
Arguments
x |
[any] |
cl |
[ |
s4 |
[ |
len |
[ |
min.len |
[ |
max.len |
[ |
choices |
[any] |
subset |
[any] |
lower |
[ |
upper |
[ |
na.ok |
[ |
formals |
[ |
Value
Nothing.
Check that a list contains only elements of a required type
Description
Check that argument is a list and contains only elements of a required type. Throws exception if check is not passed. Note that argument is evaluated when checked.
Usage
checkListElementClass(xs, cl)
Arguments
xs |
[ |
cl |
[ |
Value
Nothing.
Examples
xs = as.list(1:3)
checkListElementClass(xs, "numeric")
Chunk elements of vectors into blocks of nearly equal size
Description
In case of shuffling and vectors that cannot be chunked evenly, it is chosen randomly which levels / chunks will receive 1 element less. If you do not shuffle, always the last chunks will receive 1 element less.
Usage
chunk(x, chunk.size, n.chunks, props, shuffle = FALSE)
Arguments
x |
[ANY] |
chunk.size |
[ |
n.chunks |
[ |
props |
[ |
shuffle |
[ |
Value
[unnamed list] of chunks.
Examples
xs = 1:10
chunk(xs, chunk.size = 3)
chunk(xs, n.chunks = 2)
chunk(xs, n.chunks = 2, shuffle = TRUE)
chunk(xs, props = c(7, 3))
Shortens strings to a given length
Description
Clips strings to a maximum length, appending a tail if shortened.
Usage
clipString(x, len, tail = "...")
Arguments
x |
[ |
len |
[ |
tail |
[ |
Value
[character(1)].
Examples
print(clipString("abcdef", 10))
print(clipString("abcdef", 5))
Returns first non-missing, non-null argument
Description
Returns first non-missing, non-null argument, otherwise NULL.
We have to perform some pretty weird tryCatch stuff internally,
so you should better not pass complex function calls into the arguments that can throw exceptions,
as these will be completely muffled, and return NULL in the end.
Usage
coalesce(...)
Arguments
... |
[any] |
Value
[any].
Examples
f = function(x,y) {
print(coalesce(NULL, x, y))
}
f(y = 3)
Collapse vector to string
Description
A simple wrapper for paste(x, collapse).
Usage
collapse(x, sep = ",")
Arguments
x |
[ |
sep |
[ |
Value
[character(1)].
Examples
collapse(c("foo", "bar"))
collapse(c("foo", "bar"), sep = ";")
Collapse vector to string
Description
A simple wrapper for collapse(sprintf, ...).
Useful for vectorized call to sprintf.
Usage
collapsef(..., sep = ",")
Arguments
... |
[any] |
sep |
[ |
Value
[character(1)].
Compute statistical mode of a vector (value that occurs most frequently)
Description
Works for integer, numeric, factor and character vectors. The implementation is currently not extremely efficient.
Usage
computeMode(x, ties.method = "random", na.rm = TRUE)
Arguments
x |
[ |
ties.method |
[ |
na.rm |
[ |
Value
Modal value of length 1, data type depends on data type of x.
Examples
computeMode(c(1,2,3,3))
Converts columns in a data frame to characters, factors or numerics
Description
Converts columns of a data frame based on specified conversion flags.
Usage
convertDataFrameCols(
df,
chars.as.factor = FALSE,
factors.as.char = FALSE,
ints.as.num = FALSE,
logicals.as.factor = FALSE
)
Arguments
df |
[ |
chars.as.factor |
[ |
factors.as.char |
[ |
ints.as.num |
[ |
logicals.as.factor |
[ |
Value
[data.frame].
Conversion for single integer
Description
Convert single numeric to integer only if the numeric represents a single integer, e.g. 1 to 1L. Otherwise the argument is returned unchanged.
Usage
convertInteger(x)
Arguments
x |
[any] |
Value
Either a single integer if conversion was done or x unchanged.
Examples
str(convertInteger(1.0))
str(convertInteger(1.3))
str(convertInteger(c(1.0, 2.0)))
str(convertInteger("foo"))
Conversion for integer vector
Description
Convert numeric vector to integer vector if the numeric vector fully represents
an integer vector,
e.g. c(1, 5) to c(1L, 5L).
Otherwise the argument is returned unchanged.
Usage
convertIntegers(x)
Arguments
x |
[any] |
Value
Either an integer vector if conversion was done or x unchanged.
Examples
str(convertIntegers(1.0))
str(convertIntegers(1.3))
str(convertIntegers(c(1.0, 2.0)))
str(convertIntegers("foo"))
Convert a list of row-vector of equal structure to a data.frame
Description
Elements are arranged in columns according to their name in each
element of rows.
Variables that are not present in some row-lists, or encoded as NULL, are filled using NAs.
Usage
convertListOfRowsToDataFrame(
rows,
strings.as.factors = NULL,
row.names,
col.names
)
Arguments
rows |
[ |
strings.as.factors |
[ |
row.names |
[ |
col.names |
[ |
Value
[data.frame].
Examples
convertListOfRowsToDataFrame(list(list(x = 1, y = "a"), list(x = 2, y = "b")))
Converts storage type of a matrix
Description
Works by setting mode.
Usage
convertMatrixType(x, type)
Arguments
x |
[ |
type |
[ |
Value
[matrix].
Note
as.mytype drops dimension when used on a matrix.
Convert rows (columns) of data.frame or matrix to lists
Description
For each row, one list/vector is constructed, each entry of the row becomes a list/vector element.
Usage
convertRowsToList(
x,
name.list = TRUE,
name.vector = FALSE,
factors.as.char = TRUE,
as.vector = TRUE
)
convertColsToList(
x,
name.list = FALSE,
name.vector = FALSE,
factors.as.char = TRUE,
as.vector = TRUE
)
Arguments
x |
[ |
name.list |
[ |
name.vector |
[ |
factors.as.char |
[ |
as.vector |
[ |
Value
[list of lists or vectors].
Converts any R object to a descriptive string so it can be used in messages
Description
Atomics: If of length 0 or 1, they are basically printed as they are.
Numerics are formated with num.format.
If of length greater than 1, they are collapsed witd “,” and clipped.
so they do not become excessively long.
Expressions will be converted to plain text.
All others: Currently, only their class is simply printed like “<data.frame>”.
Lists: The mechanism above is applied (non-recursively) to their elements. The result looks like this: “a=1, <unamed>=2, b=<data.frame>, c=<list>”.
Usage
convertToShortString(x, num.format = "%.4g", clip.len = 15L)
Arguments
x |
[any] |
num.format |
[ |
clip.len |
[ |
Value
[character(1)].
Examples
convertToShortString(list(a = 1, b = NULL, "foo", c = 1:10))
Call lapply on an object and return a data.frame
Description
Applies a function fun on each element of input x
and combines the results as data.frame columns.
The results will get replicated to have equal length
if necessary and possible.
Usage
dapply(x, fun, ..., col.names)
Arguments
x |
[ |
fun |
[ |
... |
[any] |
col.names |
[ |
Value
[data.frame].
Deprecated function. Do not use!
Description
These functions are deprecated and will be removed in future versions.
Usage
convertDfCols(
df,
chars.as.factor = FALSE,
factors.as.char = FALSE,
ints.as.num = FALSE,
logicals.as.factor = FALSE
)
listToShortString(x, num.format = "%.4g", clip.len = 15L)
Arguments
df |
No text |
chars.as.factor |
No text |
factors.as.char |
No text |
ints.as.num |
No text |
logicals.as.factor |
No text |
x |
No text |
num.format |
No text |
clip.len |
No text |
Execute a function call similar to do.call
Description
This function is supposed to be a replacement for do.call in situations
where you need to pass big R objects.
Unlike do.call, this function allows to pass objects via ...
to avoid a copy.
Usage
do.call2(fun, ..., .args = list())
Arguments
fun |
[ |
... |
[any] |
.args |
[ |
Value
Return value of fun.
Examples
## Not run:
library(microbenchmark)
x = 1:1e7
microbenchmark(do.call(head, list(x, n = 1)), do.call2("head", x, n = 1))
## End(Not run)
Drop named elements of an object
Description
Removes named elements from a vector, list, matrix or data frame.
Usage
dropNamed(x, drop = character(0L))
Arguments
x |
[any] |
drop |
[ |
Value
Subset of object of same type as x. The object is not simplified,
i.e, no dimensions are dropped as [,,drop = FALSE] is used.
Blow up single scalars / objects to vectors / list by replication
Description
Useful for standard argument conversion where a user can input a single element, but this has to be replicated now n times for a resulting vector or list.
Usage
ensureVector(x, n = 1L, cl = NULL, names = NULL, ensure.list = FALSE)
Arguments
x |
[any] |
n |
[ |
cl |
[ |
names |
[ |
ensure.list |
[ |
Value
Ether a vector or list of length n with replicated x or x unchanged..
Split up a string into substrings
Description
Split up a string into substrings according to a seperator.
Usage
explode(x, sep = " ")
Arguments
x |
[ |
sep |
[ |
Value
[vector]
Vector of substrings.
Examples
explode("foo bar")
explode("comma,seperated,values", sep = ",")
Extracts a named element from a list of lists
Description
Extracts elements from a list of named lists by element name.
Usage
extractSubList(xs, element, element.value, simplify = TRUE, use.names = TRUE)
Arguments
xs |
[ |
element |
[ |
element.value |
[any] |
simplify |
[ |
use.names |
[ |
Value
[list | simplified vector | matrix]. See above.
Examples
xs = list(list(a = 1, b = 2), list(a = 5, b = 7))
extractSubList(xs, "a")
extractSubList(xs, "a", simplify = FALSE)
Filter a list for NULL values
Description
Removes all NULL elements from a list.
Usage
filterNull(li)
Arguments
li |
[ |
Value
[list].
Helper function for determining the vector of attribute names of a given object
Description
Returns the names of all attributes of an object.
Usage
getAttributeNames(obj)
Arguments
obj |
[any] |
Value
[character]
Vector of attribute names for the source object.
Wrapper for class(x)[1]
Description
Returns the first class of an object.
Usage
getClass1(x)
Arguments
x |
[any] |
Value
[character(1)].
Note
getClass is a function in methods. Do not confuse.
Get the first/last element of a list/vector
Description
Returns the first or last element of a list or vector.
Usage
getFirst(x)
getLast(x)
Arguments
x |
[ |
Value
Selected element. The element name is dropped.
Return index of maximal/minimal/best element in numerical vector
Description
If x is empty or only contains NAs which are to be removed,
-1 is returned.
Usage
getMaxIndex(x, weights = NULL, ties.method = "random", na.rm = FALSE)
getMinIndex(x, weights = NULL, ties.method = "random", na.rm = FALSE)
getBestIndex(x, weights = NULL, minimize = TRUE, ...)
Arguments
x |
[ |
weights |
[ |
ties.method |
[ |
na.rm |
[ |
minimize |
[ |
... |
[any] |
Value
[integer(1)].
Note
Function getBestIndex is a simple wrapper for getMinIndex or
getMaxIndex respectively depending on the argument minimize.
Find row- or columnwise the index of the maximal / minimal element in a matrix
Description
getMaxIndexOfRows returns the index of the maximal element of each row.
getMinIndexOfRows returns the index of the minimal element of each row.
getMaxIndexOfCols returns the index of the maximal element of each col.
getMinIndexOfCols returns the index of the minimal element of each col.
If a corresponding vector (row or col) is empty, possibly after NA removal, -1 is returned
as index.
Usage
getMaxIndexOfRows(x, weights = NULL, ties.method = "random", na.rm = FALSE)
getMinIndexOfRows(x, weights = NULL, ties.method = "random", na.rm = FALSE)
getMaxIndexOfCols(x, weights = NULL, ties.method = "random", na.rm = FALSE)
getMinIndexOfCols(x, weights = NULL, ties.method = "random", na.rm = FALSE)
Arguments
x |
[ |
weights |
[ |
ties.method |
[ |
na.rm |
[ |
Value
[integer(n)].
Examples
x = matrix(runif(5 * 3), ncol = 3)
print(x)
print(getMaxIndexOfRows(x))
print(getMinIndexOfRows(x))
Functions to determine the operating system
Description
- getOperatingSystem
Simple wrapper for
.Platform$OS.type, returnscharacter(1).- isUnix
Predicate for OS string, returns
logical(1). Currently this would include Unix, Linux and Mac flavours.- isLinux
Predicate for sysname string, returns
logical(1).- isDarwin
Predicate for sysname string, returns
logical(1).- isWindows
Predicate for OS string, returns
logical(1).
Usage
getOperatingSystem()
isWindows()
isUnix()
isLinux()
isDarwin()
Value
See above.
Construct a path relative to another
Description
Constructs a relative path from path from to path to.
If this is not possible (i.e. different drive letters on windows systems),
NA is returned.
Usage
getRelativePath(to, from = getwd(), ignore.case = isWindows())
Arguments
to |
[ |
from |
[ |
ignore.case |
[ |
Value
[character(1)]: A relative path.
Current time in seconds
Description
Simple wrapper for as.integer(Sys.time()).
Usage
getUnixTime()
Value
[integer(1)].
Determines used factor levels
Description
Determines the factor levels of a factor type vector that are actually occuring in it.
Usage
getUsedFactorLevels(x)
Arguments
x |
[ |
Value
[character]
Check if given object has certain attributes
Description
Checks whether an object has all specified attributes.
Usage
hasAttributes(obj, attribute.names)
Arguments
obj |
[mixed] |
attribute.names |
[ |
Value
[logical(1)]
TRUE if object x contains all attributes from attributeNames
and FALSE otherwise.
Insert elements from one list/vector into another list/vector
Description
Inserts elements from xs2 into xs1 by name,
overwriting elements of equal names.
Usage
insert(xs1, xs2, elements)
Arguments
xs1 |
[ |
xs2 |
[ |
elements |
[ |
Value
x1 with replaced elements from x2.
Examples
xs1 = list(a = 1, b = 2)
xs2 = list(b = 1, c = 4)
insert(xs1, xs2)
insert(xs1, xs2, elements = "c")
Is return value of try an exception?
Description
Checks if an object is of class “try-error” or “error”.
Usage
is.error(x)
Arguments
x |
[any] |
Value
[logical(1)].
Examples
x = try(stop("foo"))
print(is.error(x))
x = 1
print(is.error(x))
Is one / are several files a directory?
Description
If a file does not exist, FALSE is returned.
Usage
isDirectory(...)
Arguments
... |
[ |
Value
[logical].
Examples
print(isDirectory(tempdir()))
print(isDirectory(tempfile()))
Is one / are several directories empty?
Description
If file does not exist or is not a directory, FALSE is returned.
Usage
isEmptyDirectory(...)
Arguments
... |
[ |
Value
[logical].
Examples
print(isEmptyDirectory(tempdir()))
print(isEmptyDirectory(tempfile()))
Conditional checking for expensive examples
Description
Queries environment variable “R_EXPENSIVE_EXAMPLE_OK”.
Returns TRUE iff set exactly to “TRUE”.
This allows conditional checking of expensive examples in packages
via R CMD CHECK, so they are not run on CRAN, but at least
on your local computer.
A better option than “dont_run” in many cases, where such examples
are not checked at all.
Usage
isExpensiveExampleOk()
Value
[logical(1)].
Examples
# extremely costly random number generation, that we dont want checked on CRAN
if (isExpensiveExampleOk()) {
runif(1)
}
A wrapper for identical(x, FALSE)
Description
Tests if an object is identical to FALSE.
Usage
isFALSE(x)
Arguments
x |
[any] |
Value
[logical(1)].
Examples
isFALSE(0)
isFALSE(FALSE)
Are all elements of a list / vector uniquely named?
Description
NA or “” are not allowed as names.
Usage
isProperlyNamed(x)
Arguments
x |
[ |
Value
[logical(1)].
Examples
isProperlyNamed(list(1))
isProperlyNamed(list(a = 1))
isProperlyNamed(list(a = 1, 2))
Checks whether an object is a scalar NA value
Description
Checks whether object is from (NA, NA_integer, NA_real_, NA_character_, NA_complex_).
Usage
isScalarNA(x)
Arguments
x |
[any] |
Value
[logical(1)].
Is given argument an atomic vector or factor of length 1?
Description
More specific functions for scalars of a given type exist, too.
Usage
isScalarValue(x, na.ok = TRUE, null.ok = FALSE, type = "atomic")
isScalarLogical(x, na.ok = TRUE, null.ok = FALSE)
isScalarNumeric(x, na.ok = TRUE, null.ok = FALSE)
isScalarInteger(x, na.ok = TRUE, null.ok = FALSE)
isScalarComplex(x, na.ok = TRUE, null.ok = FALSE)
isScalarCharacter(x, na.ok = TRUE, null.ok = FALSE)
isScalarFactor(x, na.ok = TRUE, null.ok = FALSE)
Arguments
x |
[any] |
na.ok |
[ |
null.ok |
[ |
type |
[ |
Value
[logical(1)].
Check subset relation on two vectors
Description
Checks if all elements of x are contained in y.
Usage
isSubset(x, y, strict = FALSE)
Arguments
x |
[ |
y |
[ |
strict |
[ |
Value
[logical(1)]
TRUE if each element of x is also contained in y, i. e.,
if x is a subset of y and FALSE otherwise.
Check superset relation on two vectors
Description
Checks if all elements of y are contained in x.
Usage
isSuperset(x, y, strict = FALSE)
Arguments
x |
[ |
y |
[ |
strict |
[ |
Value
[logical(1)]
TRUE if each element of y is also contained in x, i. e.,
if y is a subset of x and FALSE otherwise.
Can some strings be used for column or list element names without problems?
Description
Checks if strings are valid R names that won't cause problems as column names.
Usage
isValidName(x, unique = TRUE)
Arguments
x |
[ |
unique |
[ |
Value
[logical]. One Boolean entry for each string in x.
If the entries are not unique and unique is enabled, the first duplicate will
be FALSE.
Convert Integers to Strings
Description
This is the counterpart of strtoi.
For a base greater than ‘10’, letters ‘a’ to ‘z’
are used to represent ‘10’ to ‘35’.
Usage
itostr(x, base = 10L)
Arguments
x |
[ |
base |
[ |
Value
character(length(x)).
Examples
# binary representation of the first 10 natural numbers
itostr(1:10, 2)
# base36 encoding of a large number
itostr(1e7, 36)
A wrapper for library
Description
Tries to load packages. If the packages are not found, they will be installed from the default repository. This function is intended for use in interactive sessions and should not be used by other packages.
Usage
lib(...)
Arguments
... |
[any] |
Value
[logical]: Named logical vector determining the success
of package load.
Examples
## Not run:
lib("BBmisc", "MASS", "rpart")
## End(Not run)
Load RData file and return objects in it
Description
Loads an RData file and returns the objects directly instead of loading them into an environment.
Usage
load2(file, parts, simplify = TRUE, envir, impute)
Arguments
file |
[ |
parts |
[ |
simplify |
[ |
envir |
[ |
impute |
[ |
Value
Either a single object or a list.
Examples
fn = tempfile()
save2(file = fn, a = 1, b = 2, c = 3)
load2(fn, parts = "a")
load2(fn, parts = c("a", "c"))
A wrapper for sort to sort using the “C” collating rules
Description
Sorts using the C locale for consistent sorting across platforms.
Usage
lsort(...)
Arguments
... |
Options passed to sort. |
Value
See sort.
Initialize data.frame in a convenient way
Description
Creates a data frame with specified dimensions, column types and optional initial values.
Usage
makeDataFrame(
nrow,
ncol,
col.types,
init,
row.names = NULL,
col.names = sprintf("V%i", seq_len(ncol))
)
Arguments
nrow |
[ |
ncol |
[ |
col.types |
[ |
init |
[any] |
row.names |
[ |
col.names |
[ |
Examples
print(makeDataFrame(3, 2, init = 7))
print(makeDataFrame(3, 2, "logical"))
print(makeDataFrame(3, 2, c("logical", "numeric")))
A caching wrapper around load2
Description
This closure returns a wrapper around load2 which per
default caches loaded objects and returns the cached version
in subsequent calls.
Usage
makeFileCache(use.cache = TRUE)
Arguments
use.cache |
[ |
Value
[function()] with argument slot
(name of the slot to cache the object in, default is “default”).
All other arguments are passed down to load2.
Create a progress bar with estimated time
Description
Create a progress bar function that displays the estimated time till
completion and optional messages. Call the returned functions set or
inc during a loop to change the display.
Note that you are not allowed to decrease the value of the bar.
If you call these function without setting any of the arguments
the bar is simply redrawn with the current value.
For errorhandling use error and have a look at the example below.
You can globally change the behavior of all bars by setting the option
options(BBmisc.ProgressBar.style) either to “text” (the default)
or “off”, which display no bars at all.
You can globally change the width of all bars by setting the option
options(BBmisc.ProgressBar.width). By default this is getOption("width").
You can globally set the stream where the output of the bar is directed by setting the option
options(BBmisc.ProgressBar.stream) either to “stderr” (the default)
or “stdout”. Note that using the latter will result in the bar being shown in
reports generated by Sweave or knitr, what you probably do not want.
Usage
makeProgressBar(
min = 0,
max = 100,
label = "",
char = "+",
style = getOption("BBmisc.ProgressBar.style", "text"),
width = getOption("BBmisc.ProgressBar.width", getOption("width")),
stream = getOption("BBmisc.ProgressBar.stream", "stderr")
)
Arguments
min |
[ |
max |
[ |
label |
[ |
char |
[ |
style |
[ |
width |
[ |
stream |
[ |
Value
[ProgressBar]. A list with following functions:
set [function(value, msg = label)] |
Set the bar to a value and possibly display a message instead of the label. |
inc [function(value, msg = label)] |
Increase the bar and possibly display a message instead of the label. |
kill [function(clear = FALSE)] |
Kill the bar so it cannot be used anymore. Cursor is moved to new line. You can also erase its display. |
error [function(e)] |
Useful in |
Examples
bar = makeProgressBar(max = 5, label = "test-bar")
for (i in 0:5) {
bar$set(i)
Sys.sleep(0.2)
}
bar = makeProgressBar(max = 5, label = "test-bar")
for (i in 1:5) {
bar$inc(1)
Sys.sleep(0.2)
}
# display errors properly (in next line)
## Not run:
f = function(i) if (i>2) stop("foo")
bar = makeProgressBar(max = 5, label = "test-bar")
for (i in 1:5) {
tryCatch ({
f(i)
bar$set(i)
}, error = bar$error)
}
## End(Not run)
Simple constructor for S3 objects based on lists
Description
Simple wrapper for as.list and setClasses.
Usage
makeS3Obj(classes, ...)
Arguments
classes |
[ |
... |
[any] |
Value
Object.
Examples
makeS3Obj("car", speed = 100, color = "red")
Simple logger which outputs to a file
Description
Creates a simple file logger closure to log to a file, including time stamps. An optional buffer holds the last few log messages.
Usage
makeSimpleFileLogger(logfile, touch = FALSE, keep = 10L)
Arguments
logfile |
[ |
touch |
[ |
keep |
[ |
Value
[SimpleFileLogger]. A list with following functions:
log [function(msg)] |
Send log message. |
getMessages [function(n)] |
Get last |
clear [function()] |
Resets logger and deletes log file. |
getSize [function()] |
Returns the number of logs written. |
getLogfile [function()] |
Returns the full file name logs are written to. |
Replace values in atomic vectors
Description
Replace values in atomic vectors
Usage
mapValues(
x,
from,
to,
regex = FALSE,
ignore.case = FALSE,
perl = FALSE,
fixed = FALSE
)
Arguments
x |
[ |
from |
[ |
to |
[ |
regex |
[ |
ignore.case |
[ |
perl |
[ |
fixed |
[ |
Details
Replaces values specified in from with values in to.
Regular expression matching can be enabled which calls gsub iteratively
on x to replace all patterns in from with replacements in to.
Value
[atomic].
Examples
# replace integers
x = 1:5
mapValues(x, c(2, 3), c(99, 100))
# replace factor levels using regex matching
x = factor(c("aab", "aba", "baa"))
mapValues(x, "a.a", "zzz", regex = TRUE)
Wrapper for message and sprintf
Description
A simple wrapper for message(sprintf(...)).
Usage
messagef(..., .newline = TRUE)
Arguments
... |
[any] |
.newline |
[logical(1)] |
Value
Nothing.
Examples
msg = "a message"
warningf("this is %s", msg)
Create named list, possibly initialized with a certain element
Description
Even an empty list will always be named.
Usage
namedList(names, init)
Arguments
names |
[ |
init |
[valid R expression] |
Value
[list].
Examples
namedList(c("a", "b"))
namedList(c("a", "b"), init = 1)
Replacement for names which always returns a vector
Description
A simple wrapper for names.
Returns a vector even if no names attribute is set.
Values NA and "" are treated as missing and
replaced with the value provided in missing.val.
Usage
names2(x, missing.val = NA_character_)
Arguments
x |
[ |
missing.val |
[ |
Value
[character]: vector of the same length as x.
Examples
x = 1:3
names(x)
names2(x)
names(x[1:2]) = letters[1:2]
names(x)
names2(x)
Normalizes numeric data to a given scale
Description
Currently implemented for numeric vectors, numeric matrices and data.frame. For matrixes one can operate on rows or columns For data.frames, only the numeric columns are touched, all others are left unchanged. For constant vectors / rows / columns most methods fail, special behaviour for this case is implemented.
The method also handles NAs in in x and leaves them untouched.
Usage
normalize(
x,
method = "standardize",
range = c(0, 1),
margin = 1L,
on.constant = "quiet"
)
Arguments
x |
[ |
method |
[ |
range |
[ |
margin |
[ |
on.constant |
[ |
Value
[numeric | matrix | data.frame].
See Also
Naive multi-start version of optimize for global optimization
Description
The univariate optimize can stop at arbitrarily bad points when
f is not unimodal. This functions mitigates this effect in a very naive way:
interval is subdivided into nsub equally sized subintervals,
optimize is run on all of them (and on the original big interval) and
the best obtained point is returned.
Usage
optimizeSubInts(
f,
interval,
...,
lower = min(interval),
upper = max(interval),
maximum = FALSE,
tol = .Machine$double.eps^0.25,
nsub = 50L
)
Arguments
f |
See |
interval |
See |
... |
See |
lower |
See |
upper |
See |
maximum |
See |
tol |
See |
nsub |
[ |
Value
See optimize.
Pause in interactive mode and continue on <Enter>.
Description
Pause in interactive mode and continue on <Enter>.
Usage
pause()
More meaningful head(df) output
Description
The behaviour is similar to print(head(x, n)). The difference is, that if
the number of rows in a data.frame/matrix or the number of elements in a list
or vector is larger than n, additional information is printed about
the total number of rows or elements respectively.
Usage
printHead(x, n = 6L)
Arguments
x |
[ |
n |
[ |
Value
Nothing.
Print str(x) of an object to a string / character vector
Description
Captures the output of str() as a character string.
Usage
printStrToChar(x, collapse = "\n")
Arguments
x |
[any] |
collapse |
[ |
Value
[character].
Examples
printStrToChar(iris)
Prints object to a string / character vector
Description
Captures the output of print() as a character string.
Usage
printToChar(x, collapse = "\n")
Arguments
x |
[any] |
collapse |
[ |
Value
[character].
Examples
x = data.frame(a = 1:2, b = 3:4)
str(printToChar(x))
Calculate range statistic
Description
A simple wrapper for diff(range(x)), so max(x) - min(x).
Usage
rangeVal(x, na.rm = FALSE)
Arguments
x |
[ |
na.rm |
[ |
Value
[numeric(1)].
Require some packages
Description
Packages are loaded either via requireNamespace or require.
If some packages could not be loaded and stop is TRUE
the following exception is thrown:
“For <why> please install the following packages: <missing packages>”.
If why is NULL the message is:
“Please install the following packages: <missing packages>”.
Usage
requirePackages(
packs,
min.versions = NULL,
why = "",
stop = TRUE,
suppress.warnings = FALSE,
default.method = "attach"
)
Arguments
packs |
[ |
min.versions |
[ |
why |
[ |
stop |
[ |
suppress.warnings |
[ |
default.method |
[ |
Value
[logical]. Named logical vector describing which packages could be loaded (with required version).
Same length as packs.
Examples
requirePackages(c("BBmisc", "base"), why = "BBmisc example")
Apply function to rows of a data frame
Description
Just like an lapply on data frames,
but on the rows.
Usage
rowLapply(df, fun, ..., unlist = FALSE)
rowSapply(df, fun, ..., unlist = FALSE, simplify = TRUE, use.names = TRUE)
Arguments
df |
[ |
fun |
[ |
... |
[ |
unlist |
[ |
simplify |
[ |
use.names |
[ |
Value
[list or simplified object]. Length is nrow(df).
Examples
rowLapply(iris, function(x) x$Sepal.Length + x$Sepal.Width)
Save multiple objects to a file
Description
A simple wrapper for save. Understands key = value syntax to save
objects using arbitrary variable names. All options of save,
except list and envir, are available and passed to
save.
Usage
save2(
file,
...,
ascii = FALSE,
version = NULL,
compress = !ascii,
compression_level,
eval.promises = TRUE,
precheck = TRUE
)
Arguments
file |
File to save. |
... |
[ |
ascii |
See help of |
version |
See help of |
compress |
See help of |
compression_level |
See help of |
eval.promises |
See help of |
precheck |
See help of |
Value
See help of save.
Examples
x = 1
save2(y = x, file = tempfile())
Generate sequences along rows or cols
Description
A simple convenience wrapper around seq_len.
Usage
seq_row(x)
seq_col(x)
Arguments
x |
[ |
Value
Vector of type [integer].
Examples
data(iris)
seq_row(iris)
seq_col(iris)
A wrapper for attr(x, which) = y
Description
Sets an attribute on an object and returns the modified object.
Usage
setAttribute(x, which, value)
Arguments
x |
[any] |
which |
[ |
value |
[ |
Value
Changed object x.
Examples
setAttribute(list(), "foo", 1)
A wrapper for class(x) = classes
Description
Sets the class attribute of an object and returns the modified object.
Usage
setClasses(x, classes)
Arguments
x |
[any] |
classes |
[ |
Value
Changed object x.
Examples
setClasses(list(), c("foo1", "foo2"))
Wrapper for rownames(x) = y, colnames(x) = y
Description
Sets row or column names on a matrix or data frame and returns the modified object.
Usage
setRowNames(x, names)
setColNames(x, names)
Arguments
x |
[ |
names |
[ |
Value
Changed object x.
Examples
setColNames(matrix(1:4, 2, 2), c("a", "b"))
Set a list element to a new value
Description
This wrapper supports setting elements to NULL.
Usage
setValue(obj, index, newval)
Arguments
obj |
[ |
index |
[ |
newval |
[any] |
Value
[list]
Sort the rows of a data.frame according to one or more columns
Description
Sorts a data frame by one or more columns in ascending or descending order.
Usage
sortByCol(x, col, asc = TRUE)
Arguments
x |
[ |
col |
[ |
asc |
[ |
Value
[data.frame].
Split a path into components
Description
The first normalized path is split on forward and backward slashes and its components returned as character vector. The drive or network home are extracted separately on windows systems and empty on all other systems.
Usage
splitPath(path)
Arguments
path |
[ |
Value
named list: List with components “drive” (character(1)
and “path” (character(n).
Split seconds into handy chunks of time
Description
Note that a year is simply defined as exactly 365 days.
Usage
splitTime(seconds, unit = "years")
Arguments
seconds |
[ |
unit |
[ |
Value
[numeric(5)]. A named vector containing the
“years”, “days”, “hours”, “minutes”
and “seconds”. Units larger than the given unit are
NA.
Examples
splitTime(1000)
Wrapper for stop and sprintf
Description
A wrapper for stop with sprintf applied to the arguments.
Notable difference is that error messages are not truncated to 1000 characters
by default.
Usage
stopf(..., warning.length = 8170L)
Arguments
... |
[any] |
warning.length |
[ |
Value
Nothing.
Examples
err = "an error."
try(stopf("This is %s", err))
Repeat and join a string
Description
Repeats a string n times and joins the results.
Usage
strrepeat(x, n, sep = "")
Arguments
x |
[character] |
n |
[ |
sep |
[ |
Value
character(1).
Examples
strrepeat("x", 3)
Suppresses all output except for errors
Description
Evaluates an expression and suppresses all output except for errors, meaning: prints, messages, warnings and package startup messages.
Usage
suppressAll(expr)
Arguments
expr |
[valid R expression] |
Value
Return value of expression invisibly.
Examples
suppressAll({
print("foo")
message("foo")
warning("foo")
})
Calculates symmetric set difference between two sets
Description
Returns elements that are in either set but not in both.
Usage
symdiff(x, y)
Arguments
x |
[ |
y |
[ |
Value
[vector].
Wrapper for system2 with better return type and errorhandling
Description
Wrapper for system2 with better return type and errorhandling.
Usage
system3(
command,
args = character(0L),
stdout = "",
stderr = "",
wait = TRUE,
...,
stop.on.exit.code = wait
)
Arguments
command |
See |
args |
See |
stdout |
See |
stderr |
See |
wait |
See |
... |
Further arguments passed to |
stop.on.exit.code |
[ |
Value
[list].
exit.code [integer(1)] |
Exit code of command. Given if wait is |
output [character] |
Output of command on streams. Only given is |
Convert a numerical vector into a range string
Description
Converts a vector of integers into a compact range string representation.
Usage
toRangeStr(x, range.sep = " - ", block.sep = ", ")
Arguments
x |
[ |
range.sep |
[ |
block.sep |
[ |
Value
[character(1)]
Examples
x = sample(1:10, 7)
toRangeStr(x)
Apply a function with a predefined return value
Description
These are just wrappers around vapply with
argument FUN.VALUE set.
The function is expected to return a single logical, integer,
numeric or character value, depending on the second letter
of the function name.
Usage
vlapply(x, fun, ..., use.names = TRUE)
viapply(x, fun, ..., use.names = TRUE)
vnapply(x, fun, ..., use.names = TRUE)
vcapply(x, fun, ..., use.names = TRUE)
Arguments
x |
[ |
fun |
[ |
... |
[ |
use.names |
[ |
Wrapper for warning and sprintf
Description
A wrapper for warning with sprintf applied to the arguments.
Usage
warningf(..., immediate = TRUE, warning.length = 8170L)
Arguments
... |
[any] |
immediate |
[ |
warning.length |
[ |
Value
Nothing.
Examples
msg = "a warning"
warningf("this is %s", msg)
Find the index of first/last TRUE value in a logical vector
Description
Returns the index of the first or last TRUE value in a logical vector.
Usage
which.first(x, use.names = TRUE)
which.last(x, use.names = TRUE)
Arguments
x |
[ |
use.names |
[ |
Value
[integer(1) | integer(0)].
Returns the index of the first/last TRUE value in x or
an empty integer vector if none is found.
Examples
which.first(c(FALSE, TRUE))
which.last(c(FALSE, FALSE))