| Title: | Miscellaneous Helper Functions for B. Bischl |
|---|---|
| Description: | Miscellaneous helper functions for and from B. Bischl and some other guys, mainly for package development. |
| Authors: | Bernd Bischl [aut, cre], Michel Lang [aut], Jakob Bossek [aut], Daniel Horn [aut], Jakob Richter [aut], Dirk Surmann [aut] |
| Maintainer: | Bernd Bischl <[email protected]> |
| License: | BSD_2_clause + file LICENSE |
| Version: | 1.13 |
| Built: | 2026-05-21 05:56:28 UTC |
| Source: | https://github.com/berndbischl/bbmisc |
Tests whether values in x are between the minimum and maximum of y.
x %btwn% yx %btwn% y
x |
[ |
y |
[ |
[logical(n)]. For each value in x: Is it in the range of y?
x = 3 y = c(-1,2,5) x %btwn% yx = 3 y = c(-1,2,5) x %btwn% y
in operatorTests if elements of x are not in y.
x %nin% yx %nin% y
x |
[ |
y |
[ |
Adds classes to the class attribute of an object.
addClasses(x, classes)addClasses(x, classes)
x |
[any] |
classes |
[ |
Changed object x.
x = list() print(class(x)) x = addClasses(x, c("foo1", "foo2")) print(class(x))x = list() print(class(x)) x = addClasses(x, c("foo1", "foo2")) print(class(x))
... arguments to a named listThe deparsed name will be used for arguments with missing names.
Missing names will be set to NA.
argsAsNamedList(...)argsAsNamedList(...)
... |
Arbitrary number of objects. |
[list]: Named list with objects.
z = 3 argsAsNamedList(x = 1, y = 2, z)z = 3 argsAsNamedList(x = 1, y = 2, z)
Converts a list of vectors into a matrix with vectors as columns or rows.
asMatrixCols(xs, row.names, col.names) asMatrixRows(xs, row.names, col.names)asMatrixCols(xs, row.names, col.names) asMatrixRows(xs, row.names, col.names)
xs |
[ |
row.names |
[ |
col.names |
[ |
[matrix].
Works the same as if you would have entered the expression and called
quote on it.
asQuoted(s, env = parent.frame())asQuoted(s, env = parent.frame())
s |
[ |
env |
[ |
Quoted expression.
asQuoted("x == 3")asQuoted("x == 3")
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.
binPack(x, capacity)binPack(x, capacity)
x |
[ |
capacity |
[ |
[integer]. Integer with values “1” to “n.bins”
indicating bin membership.
x = 1:10 bp = binPack(x, 11) xs = split(x, bp) print(xs) print(sapply(xs, sum))x = 1:10 bp = binPack(x, 11) xs = split(x, bp) print(xs) print(sapply(xs, sum))
Capitalise first word or all words of a character vector. Lower back of vector element or word, respectively.
capitalizeStrings(x, all.words = FALSE, lower.back = FALSE)capitalizeStrings(x, all.words = FALSE, lower.back = FALSE)
x |
[ |
all.words |
[ |
lower.back |
[ |
Capitalized vector: [character(n)].
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)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)
A simple wrapper for cat(sprintf(...)).
catf(..., file = "", append = FALSE, newline = TRUE)catf(..., file = "", append = FALSE, newline = TRUE)
... |
[any] |
file |
[ |
append |
[ |
newline |
[ |
Nothing.
msg = "a message." catf("This is %s", msg)msg = "a message." catf("This is %s", msg)
Note that function does not inherit from c to not change R semantics behind your back when this
package is loaded.
cFactor(...)cFactor(...)
... |
[ |
[factor].
f1 = factor(c("a", "b")) f2 = factor(c("b", "c")) print(c(f1, f2)) print(cFactor(f1, f2))f1 = factor(c("a", "b")) f2 = factor(c("b", "c")) print(c(f1, f2)) print(cFactor(f1, f2))
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
checkArg( x, cl, s4 = FALSE, len, min.len, max.len, choices, subset, lower = NA, upper = NA, na.ok = TRUE, formals )checkArg( x, cl, s4 = FALSE, len, min.len, max.len, choices, subset, lower = NA, upper = NA, na.ok = TRUE, formals )
x |
[any] |
cl |
[ |
s4 |
[ |
len |
[ |
min.len |
[ |
max.len |
[ |
choices |
[any] |
subset |
[any] |
lower |
[ |
upper |
[ |
na.ok |
[ |
formals |
[ |
Nothing.
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.
checkListElementClass(xs, cl)checkListElementClass(xs, cl)
xs |
[ |
cl |
[ |
Nothing.
xs = as.list(1:3) checkListElementClass(xs, "numeric")xs = as.list(1:3) checkListElementClass(xs, "numeric")
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.
chunk(x, chunk.size, n.chunks, props, shuffle = FALSE)chunk(x, chunk.size, n.chunks, props, shuffle = FALSE)
x |
[ANY] |
chunk.size |
[ |
n.chunks |
[ |
props |
[ |
shuffle |
[ |
[unnamed list] of chunks.
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))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))
Clips strings to a maximum length, appending a tail if shortened.
clipString(x, len, tail = "...")clipString(x, len, tail = "...")
x |
[ |
len |
[ |
tail |
[ |
[character(1)].
print(clipString("abcdef", 10)) print(clipString("abcdef", 5))print(clipString("abcdef", 10)) print(clipString("abcdef", 5))
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.
coalesce(...)coalesce(...)
... |
[any] |
[any].
f = function(x,y) { print(coalesce(NULL, x, y)) } f(y = 3)f = function(x,y) { print(coalesce(NULL, x, y)) } f(y = 3)
A simple wrapper for paste(x, collapse).
collapse(x, sep = ",")collapse(x, sep = ",")
x |
[ |
sep |
[ |
[character(1)].
collapse(c("foo", "bar")) collapse(c("foo", "bar"), sep = ";")collapse(c("foo", "bar")) collapse(c("foo", "bar"), sep = ";")
A simple wrapper for collapse(sprintf, ...).
Useful for vectorized call to sprintf.
collapsef(..., sep = ",")collapsef(..., sep = ",")
... |
[any] |
sep |
[ |
[character(1)].
Works for integer, numeric, factor and character vectors. The implementation is currently not extremely efficient.
computeMode(x, ties.method = "random", na.rm = TRUE)computeMode(x, ties.method = "random", na.rm = TRUE)
x |
[ |
ties.method |
[ |
na.rm |
[ |
Modal value of length 1, data type depends on data type of x.
computeMode(c(1,2,3,3))computeMode(c(1,2,3,3))
Converts columns of a data frame based on specified conversion flags.
convertDataFrameCols( df, chars.as.factor = FALSE, factors.as.char = FALSE, ints.as.num = FALSE, logicals.as.factor = FALSE )convertDataFrameCols( df, chars.as.factor = FALSE, factors.as.char = FALSE, ints.as.num = FALSE, logicals.as.factor = FALSE )
df |
[ |
chars.as.factor |
[ |
factors.as.char |
[ |
ints.as.num |
[ |
logicals.as.factor |
[ |
[data.frame].
Convert single numeric to integer only if the numeric represents a single integer, e.g. 1 to 1L. Otherwise the argument is returned unchanged.
convertInteger(x)convertInteger(x)
x |
[any] |
Either a single integer if conversion was done or x unchanged.
str(convertInteger(1.0)) str(convertInteger(1.3)) str(convertInteger(c(1.0, 2.0))) str(convertInteger("foo"))str(convertInteger(1.0)) str(convertInteger(1.3)) str(convertInteger(c(1.0, 2.0))) str(convertInteger("foo"))
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.
convertIntegers(x)convertIntegers(x)
x |
[any] |
Either an integer vector if conversion was done or x unchanged.
str(convertIntegers(1.0)) str(convertIntegers(1.3)) str(convertIntegers(c(1.0, 2.0))) str(convertIntegers("foo"))str(convertIntegers(1.0)) str(convertIntegers(1.3)) str(convertIntegers(c(1.0, 2.0))) str(convertIntegers("foo"))
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.
convertListOfRowsToDataFrame( rows, strings.as.factors = NULL, row.names, col.names )convertListOfRowsToDataFrame( rows, strings.as.factors = NULL, row.names, col.names )
rows |
[ |
strings.as.factors |
[ |
row.names |
[ |
col.names |
[ |
[data.frame].
convertListOfRowsToDataFrame(list(list(x = 1, y = "a"), list(x = 2, y = "b")))convertListOfRowsToDataFrame(list(list(x = 1, y = "a"), list(x = 2, y = "b")))
Works by setting mode.
convertMatrixType(x, type)convertMatrixType(x, type)
x |
[ |
type |
[ |
[matrix].
as.mytype drops dimension when used on a matrix.
For each row, one list/vector is constructed, each entry of the row becomes a list/vector element.
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 )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 )
x |
[ |
name.list |
[ |
name.vector |
[ |
factors.as.char |
[ |
as.vector |
[ |
[list of lists or vectors].
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>”.
convertToShortString(x, num.format = "%.4g", clip.len = 15L)convertToShortString(x, num.format = "%.4g", clip.len = 15L)
x |
[any] |
num.format |
[ |
clip.len |
[ |
[character(1)].
convertToShortString(list(a = 1, b = NULL, "foo", c = 1:10))convertToShortString(list(a = 1, b = NULL, "foo", c = 1:10))
lapply on an object and return a data.frameApplies 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.
dapply(x, fun, ..., col.names)dapply(x, fun, ..., col.names)
x |
[ |
fun |
[ |
... |
[any] |
col.names |
[ |
[data.frame].
These functions are deprecated and will be removed in future versions.
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)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)
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 |
do.call
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.
do.call2(fun, ..., .args = list())do.call2(fun, ..., .args = list())
fun |
[ |
... |
[any] |
.args |
[ |
Return value of fun.
## Not run: library(microbenchmark) x = 1:1e7 microbenchmark(do.call(head, list(x, n = 1)), do.call2("head", x, n = 1)) ## End(Not run)## Not run: library(microbenchmark) x = 1:1e7 microbenchmark(do.call(head, list(x, n = 1)), do.call2("head", x, n = 1)) ## End(Not run)
Removes named elements from a vector, list, matrix or data frame.
dropNamed(x, drop = character(0L))dropNamed(x, drop = character(0L))
x |
[any] |
drop |
[ |
Subset of object of same type as x. The object is not simplified,
i.e, no dimensions are dropped as [,,drop = FALSE] is used.
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.
ensureVector(x, n = 1L, cl = NULL, names = NULL, ensure.list = FALSE)ensureVector(x, n = 1L, cl = NULL, names = NULL, ensure.list = FALSE)
x |
[any] |
n |
[ |
cl |
[ |
names |
[ |
ensure.list |
[ |
Ether a vector or list of length n with replicated x or x unchanged..
Split up a string into substrings according to a seperator.
explode(x, sep = " ")explode(x, sep = " ")
x |
[ |
sep |
[ |
[vector]
Vector of substrings.
explode("foo bar") explode("comma,seperated,values", sep = ",")explode("foo bar") explode("comma,seperated,values", sep = ",")
Extracts elements from a list of named lists by element name.
extractSubList(xs, element, element.value, simplify = TRUE, use.names = TRUE)extractSubList(xs, element, element.value, simplify = TRUE, use.names = TRUE)
xs |
[ |
element |
[ |
element.value |
[any] |
simplify |
[ |
use.names |
[ |
[list | simplified vector | matrix]. See above.
xs = list(list(a = 1, b = 2), list(a = 5, b = 7)) extractSubList(xs, "a") extractSubList(xs, "a", simplify = FALSE)xs = list(list(a = 1, b = 2), list(a = 5, b = 7)) extractSubList(xs, "a") extractSubList(xs, "a", simplify = FALSE)
Removes all NULL elements from a list.
filterNull(li)filterNull(li)
li |
[ |
[list].
Returns the names of all attributes of an object.
getAttributeNames(obj)getAttributeNames(obj)
obj |
[any] |
[character]
Vector of attribute names for the source object.
class(x)[1]
Returns the first class of an object.
getClass1(x)getClass1(x)
x |
[any] |
[character(1)].
getClass is a function in methods. Do not confuse.
Returns the first or last element of a list or vector.
getFirst(x) getLast(x)getFirst(x) getLast(x)
x |
[ |
Selected element. The element name is dropped.
If x is empty or only contains NAs which are to be removed,
-1 is returned.
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, ...)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, ...)
x |
[ |
weights |
[ |
ties.method |
[ |
na.rm |
[ |
minimize |
[ |
... |
[any] |
[integer(1)].
Function getBestIndex is a simple wrapper for getMinIndex or
getMaxIndex respectively depending on the argument minimize.
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.
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)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)
x |
[ |
weights |
[ |
ties.method |
[ |
na.rm |
[ |
[integer(n)].
x = matrix(runif(5 * 3), ncol = 3) print(x) print(getMaxIndexOfRows(x)) print(getMinIndexOfRows(x))x = matrix(runif(5 * 3), ncol = 3) print(x) print(getMaxIndexOfRows(x)) print(getMinIndexOfRows(x))
Simple wrapper for .Platform$OS.type, returns character(1).
Predicate for OS string, returns logical(1). Currently this would include Unix, Linux and Mac flavours.
Predicate for sysname string, returns logical(1).
Predicate for sysname string, returns logical(1).
Predicate for OS string, returns logical(1).
getOperatingSystem() isWindows() isUnix() isLinux() isDarwin()getOperatingSystem() isWindows() isUnix() isLinux() isDarwin()
See above.
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.
getRelativePath(to, from = getwd(), ignore.case = isWindows())getRelativePath(to, from = getwd(), ignore.case = isWindows())
to |
[ |
from |
[ |
ignore.case |
[ |
[character(1)]: A relative path.
Simple wrapper for as.integer(Sys.time()).
getUnixTime()getUnixTime()
[integer(1)].
Determines the factor levels of a factor type vector that are actually occuring in it.
getUsedFactorLevels(x)getUsedFactorLevels(x)
x |
[ |
[character]
Checks whether an object has all specified attributes.
hasAttributes(obj, attribute.names)hasAttributes(obj, attribute.names)
obj |
[mixed] |
attribute.names |
[ |
[logical(1)]
TRUE if object x contains all attributes from attributeNames
and FALSE otherwise.
Inserts elements from xs2 into xs1 by name,
overwriting elements of equal names.
insert(xs1, xs2, elements)insert(xs1, xs2, elements)
xs1 |
[ |
xs2 |
[ |
elements |
[ |
x1 with replaced elements from x2.
xs1 = list(a = 1, b = 2) xs2 = list(b = 1, c = 4) insert(xs1, xs2) insert(xs1, xs2, elements = "c")xs1 = list(a = 1, b = 2) xs2 = list(b = 1, c = 4) insert(xs1, xs2) insert(xs1, xs2, elements = "c")
Checks if an object is of class “try-error” or “error”.
is.error(x)is.error(x)
x |
[any] |
[logical(1)].
x = try(stop("foo")) print(is.error(x)) x = 1 print(is.error(x))x = try(stop("foo")) print(is.error(x)) x = 1 print(is.error(x))
If a file does not exist, FALSE is returned.
isDirectory(...)isDirectory(...)
... |
[ |
[logical].
print(isDirectory(tempdir())) print(isDirectory(tempfile()))print(isDirectory(tempdir())) print(isDirectory(tempfile()))
If file does not exist or is not a directory, FALSE is returned.
isEmptyDirectory(...)isEmptyDirectory(...)
... |
[ |
[logical].
print(isEmptyDirectory(tempdir())) print(isEmptyDirectory(tempfile()))print(isEmptyDirectory(tempdir())) print(isEmptyDirectory(tempfile()))
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.
isExpensiveExampleOk()isExpensiveExampleOk()
[logical(1)].
# extremely costly random number generation, that we dont want checked on CRAN if (isExpensiveExampleOk()) { runif(1) }# extremely costly random number generation, that we dont want checked on CRAN if (isExpensiveExampleOk()) { runif(1) }
identical(x, FALSE)
Tests if an object is identical to FALSE.
isFALSE(x)isFALSE(x)
x |
[any] |
[logical(1)].
isFALSE(0) isFALSE(FALSE)isFALSE(0) isFALSE(FALSE)
NA or “” are not allowed as names.
isProperlyNamed(x)isProperlyNamed(x)
x |
[ |
[logical(1)].
isProperlyNamed(list(1)) isProperlyNamed(list(a = 1)) isProperlyNamed(list(a = 1, 2))isProperlyNamed(list(1)) isProperlyNamed(list(a = 1)) isProperlyNamed(list(a = 1, 2))
Checks whether object is from (NA, NA_integer, NA_real_, NA_character_, NA_complex_).
isScalarNA(x)isScalarNA(x)
x |
[any] |
[logical(1)].
More specific functions for scalars of a given type exist, too.
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)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)
x |
[any] |
na.ok |
[ |
null.ok |
[ |
type |
[ |
[logical(1)].
Checks if all elements of x are contained in y.
isSubset(x, y, strict = FALSE)isSubset(x, y, strict = FALSE)
x |
[ |
y |
[ |
strict |
[ |
[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.
Checks if all elements of y are contained in x.
isSuperset(x, y, strict = FALSE)isSuperset(x, y, strict = FALSE)
x |
[ |
y |
[ |
strict |
[ |
[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.
Checks if strings are valid R names that won't cause problems as column names.
isValidName(x, unique = TRUE)isValidName(x, unique = TRUE)
x |
[ |
unique |
[ |
[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.
This is the counterpart of strtoi.
For a base greater than ‘10’, letters ‘a’ to ‘z’
are used to represent ‘10’ to ‘35’.
itostr(x, base = 10L)itostr(x, base = 10L)
x |
[ |
base |
[ |
character(length(x)).
# binary representation of the first 10 natural numbers itostr(1:10, 2) # base36 encoding of a large number itostr(1e7, 36)# binary representation of the first 10 natural numbers itostr(1:10, 2) # base36 encoding of a large number itostr(1e7, 36)
library
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.
lib(...)lib(...)
... |
[any] |
[logical]: Named logical vector determining the success
of package load.
## Not run: lib("BBmisc", "MASS", "rpart") ## End(Not run)## Not run: lib("BBmisc", "MASS", "rpart") ## End(Not run)
Loads an RData file and returns the objects directly instead of loading them into an environment.
load2(file, parts, simplify = TRUE, envir, impute)load2(file, parts, simplify = TRUE, envir, impute)
file |
[ |
parts |
[ |
simplify |
[ |
envir |
[ |
impute |
[ |
Either a single object or a list.
fn = tempfile() save2(file = fn, a = 1, b = 2, c = 3) load2(fn, parts = "a") load2(fn, parts = c("a", "c"))fn = tempfile() save2(file = fn, a = 1, b = 2, c = 3) load2(fn, parts = "a") load2(fn, parts = c("a", "c"))
sort to sort using the “C” collating rulesSorts using the C locale for consistent sorting across platforms.
lsort(...)lsort(...)
... |
Options passed to sort. |
See sort.
Creates a data frame with specified dimensions, column types and optional initial values.
makeDataFrame( nrow, ncol, col.types, init, row.names = NULL, col.names = sprintf("V%i", seq_len(ncol)) )makeDataFrame( nrow, ncol, col.types, init, row.names = NULL, col.names = sprintf("V%i", seq_len(ncol)) )
nrow |
[ |
ncol |
[ |
col.types |
[ |
init |
[any] |
row.names |
[ |
col.names |
[ |
print(makeDataFrame(3, 2, init = 7)) print(makeDataFrame(3, 2, "logical")) print(makeDataFrame(3, 2, c("logical", "numeric")))print(makeDataFrame(3, 2, init = 7)) print(makeDataFrame(3, 2, "logical")) print(makeDataFrame(3, 2, c("logical", "numeric")))
This closure returns a wrapper around load2 which per
default caches loaded objects and returns the cached version
in subsequent calls.
makeFileCache(use.cache = TRUE)makeFileCache(use.cache = TRUE)
use.cache |
[ |
[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 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.
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") )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") )
min |
[ |
max |
[ |
label |
[ |
char |
[ |
style |
[ |
width |
[ |
stream |
[ |
[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 |
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)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 wrapper for as.list and setClasses.
makeS3Obj(classes, ...)makeS3Obj(classes, ...)
classes |
[ |
... |
[any] |
Object.
makeS3Obj("car", speed = 100, color = "red")makeS3Obj("car", speed = 100, color = "red")
Creates a simple file logger closure to log to a file, including time stamps. An optional buffer holds the last few log messages.
makeSimpleFileLogger(logfile, touch = FALSE, keep = 10L)makeSimpleFileLogger(logfile, touch = FALSE, keep = 10L)
logfile |
[ |
touch |
[ |
keep |
[ |
[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
mapValues( x, from, to, regex = FALSE, ignore.case = FALSE, perl = FALSE, fixed = FALSE )mapValues( x, from, to, regex = FALSE, ignore.case = FALSE, perl = FALSE, fixed = FALSE )
x |
[ |
from |
[ |
to |
[ |
regex |
[ |
ignore.case |
[ |
perl |
[ |
fixed |
[ |
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.
[atomic].
# 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)# 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)
A simple wrapper for message(sprintf(...)).
messagef(..., .newline = TRUE)messagef(..., .newline = TRUE)
... |
[any] |
.newline |
[logical(1)] |
Nothing.
msg = "a message" warningf("this is %s", msg)msg = "a message" warningf("this is %s", msg)
Even an empty list will always be named.
namedList(names, init)namedList(names, init)
names |
[ |
init |
[valid R expression] |
[list].
namedList(c("a", "b")) namedList(c("a", "b"), init = 1)namedList(c("a", "b")) namedList(c("a", "b"), init = 1)
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.
names2(x, missing.val = NA_character_)names2(x, missing.val = NA_character_)
x |
[ |
missing.val |
[ |
[character]: vector of the same length as x.
x = 1:3 names(x) names2(x) names(x[1:2]) = letters[1:2] names(x) names2(x)x = 1:3 names(x) names2(x) names(x[1:2]) = letters[1:2] names(x) names2(x)
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.
normalize( x, method = "standardize", range = c(0, 1), margin = 1L, on.constant = "quiet" )normalize( x, method = "standardize", range = c(0, 1), margin = 1L, on.constant = "quiet" )
x |
[ |
method |
[ |
range |
[ |
margin |
[ |
on.constant |
[ |
[numeric | matrix | data.frame].
optimize for global optimizationThe 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.
optimizeSubInts( f, interval, ..., lower = min(interval), upper = max(interval), maximum = FALSE, tol = .Machine$double.eps^0.25, nsub = 50L )optimizeSubInts( f, interval, ..., lower = min(interval), upper = max(interval), maximum = FALSE, tol = .Machine$double.eps^0.25, nsub = 50L )
f |
See |
interval |
See |
... |
See |
lower |
See |
upper |
See |
maximum |
See |
tol |
See |
nsub |
[ |
See optimize.
Pause in interactive mode and continue on <Enter>.
pause()pause()
head(df) outputThe 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.
printHead(x, n = 6L)printHead(x, n = 6L)
x |
[ |
n |
[ |
Nothing.
str(x) of an object to a string / character vectorCaptures the output of str() as a character string.
printStrToChar(x, collapse = "\n")printStrToChar(x, collapse = "\n")
x |
[any] |
collapse |
[ |
[character].
printStrToChar(iris)printStrToChar(iris)
Captures the output of print() as a character string.
printToChar(x, collapse = "\n")printToChar(x, collapse = "\n")
x |
[any] |
collapse |
[ |
[character].
x = data.frame(a = 1:2, b = 3:4) str(printToChar(x))x = data.frame(a = 1:2, b = 3:4) str(printToChar(x))
A simple wrapper for diff(range(x)), so max(x) - min(x).
rangeVal(x, na.rm = FALSE)rangeVal(x, na.rm = FALSE)
x |
[ |
na.rm |
[ |
[numeric(1)].
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>”.
requirePackages( packs, min.versions = NULL, why = "", stop = TRUE, suppress.warnings = FALSE, default.method = "attach" )requirePackages( packs, min.versions = NULL, why = "", stop = TRUE, suppress.warnings = FALSE, default.method = "attach" )
packs |
[ |
min.versions |
[ |
why |
[ |
stop |
[ |
suppress.warnings |
[ |
default.method |
[ |
[logical]. Named logical vector describing which packages could be loaded (with required version).
Same length as packs.
requirePackages(c("BBmisc", "base"), why = "BBmisc example")requirePackages(c("BBmisc", "base"), why = "BBmisc example")
Just like an lapply on data frames,
but on the rows.
rowLapply(df, fun, ..., unlist = FALSE) rowSapply(df, fun, ..., unlist = FALSE, simplify = TRUE, use.names = TRUE)rowLapply(df, fun, ..., unlist = FALSE) rowSapply(df, fun, ..., unlist = FALSE, simplify = TRUE, use.names = TRUE)
df |
[ |
fun |
[ |
... |
[ |
unlist |
[ |
simplify |
[ |
use.names |
[ |
[list or simplified object]. Length is nrow(df).
rowLapply(iris, function(x) x$Sepal.Length + x$Sepal.Width)rowLapply(iris, function(x) x$Sepal.Length + x$Sepal.Width)
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.
save2( file, ..., ascii = FALSE, version = NULL, compress = !ascii, compression_level, eval.promises = TRUE, precheck = TRUE )save2( file, ..., ascii = FALSE, version = NULL, compress = !ascii, compression_level, eval.promises = TRUE, precheck = TRUE )
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 |
See help of save.
x = 1 save2(y = x, file = tempfile())x = 1 save2(y = x, file = tempfile())
A simple convenience wrapper around seq_len.
seq_row(x) seq_col(x)seq_row(x) seq_col(x)
x |
[ |
Vector of type [integer].
data(iris) seq_row(iris) seq_col(iris)data(iris) seq_row(iris) seq_col(iris)
attr(x, which) = y
Sets an attribute on an object and returns the modified object.
setAttribute(x, which, value)setAttribute(x, which, value)
x |
[any] |
which |
[ |
value |
[ |
Changed object x.
setAttribute(list(), "foo", 1)setAttribute(list(), "foo", 1)
class(x) = classes
Sets the class attribute of an object and returns the modified object.
setClasses(x, classes)setClasses(x, classes)
x |
[any] |
classes |
[ |
Changed object x.
setClasses(list(), c("foo1", "foo2"))setClasses(list(), c("foo1", "foo2"))
rownames(x) = y, colnames(x) = y
Sets row or column names on a matrix or data frame and returns the modified object.
setRowNames(x, names) setColNames(x, names)setRowNames(x, names) setColNames(x, names)
x |
[ |
names |
[ |
Changed object x.
setColNames(matrix(1:4, 2, 2), c("a", "b"))setColNames(matrix(1:4, 2, 2), c("a", "b"))
This wrapper supports setting elements to NULL.
setValue(obj, index, newval)setValue(obj, index, newval)
obj |
[ |
index |
[ |
newval |
[any] |
[list]
Sorts a data frame by one or more columns in ascending or descending order.
sortByCol(x, col, asc = TRUE)sortByCol(x, col, asc = TRUE)
x |
[ |
col |
[ |
asc |
[ |
[data.frame].
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.
splitPath(path)splitPath(path)
path |
[ |
named list: List with components “drive” (character(1)
and “path” (character(n).
Note that a year is simply defined as exactly 365 days.
splitTime(seconds, unit = "years")splitTime(seconds, unit = "years")
seconds |
[ |
unit |
[ |
[numeric(5)]. A named vector containing the
“years”, “days”, “hours”, “minutes”
and “seconds”. Units larger than the given unit are
NA.
splitTime(1000)splitTime(1000)
A wrapper for stop with sprintf applied to the arguments.
Notable difference is that error messages are not truncated to 1000 characters
by default.
stopf(..., warning.length = 8170L)stopf(..., warning.length = 8170L)
... |
[any] |
warning.length |
[ |
Nothing.
err = "an error." try(stopf("This is %s", err))err = "an error." try(stopf("This is %s", err))
Repeats a string n times and joins the results.
strrepeat(x, n, sep = "")strrepeat(x, n, sep = "")
x |
[character] |
n |
[ |
sep |
[ |
character(1).
strrepeat("x", 3)strrepeat("x", 3)
Evaluates an expression and suppresses all output except for errors, meaning: prints, messages, warnings and package startup messages.
suppressAll(expr)suppressAll(expr)
expr |
[valid R expression] |
Return value of expression invisibly.
suppressAll({ print("foo") message("foo") warning("foo") })suppressAll({ print("foo") message("foo") warning("foo") })
Returns elements that are in either set but not in both.
symdiff(x, y)symdiff(x, y)
x |
[ |
y |
[ |
[vector].
Wrapper for system2 with better return type and errorhandling.
system3( command, args = character(0L), stdout = "", stderr = "", wait = TRUE, ..., stop.on.exit.code = wait )system3( command, args = character(0L), stdout = "", stderr = "", wait = TRUE, ..., stop.on.exit.code = wait )
command |
See |
args |
See |
stdout |
See |
stderr |
See |
wait |
See |
... |
Further arguments passed to |
stop.on.exit.code |
[ |
[list].
exit.code [integer(1)] |
Exit code of command. Given if wait is |
output [character] |
Output of command on streams. Only given is |
Converts a vector of integers into a compact range string representation.
toRangeStr(x, range.sep = " - ", block.sep = ", ")toRangeStr(x, range.sep = " - ", block.sep = ", ")
x |
[ |
range.sep |
[ |
block.sep |
[ |
[character(1)]
x = sample(1:10, 7) toRangeStr(x)x = sample(1:10, 7) toRangeStr(x)
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.
vlapply(x, fun, ..., use.names = TRUE) viapply(x, fun, ..., use.names = TRUE) vnapply(x, fun, ..., use.names = TRUE) vcapply(x, fun, ..., use.names = TRUE)vlapply(x, fun, ..., use.names = TRUE) viapply(x, fun, ..., use.names = TRUE) vnapply(x, fun, ..., use.names = TRUE) vcapply(x, fun, ..., use.names = TRUE)
x |
[ |
fun |
[ |
... |
[ |
use.names |
[ |
A wrapper for warning with sprintf applied to the arguments.
warningf(..., immediate = TRUE, warning.length = 8170L)warningf(..., immediate = TRUE, warning.length = 8170L)
... |
[any] |
immediate |
[ |
warning.length |
[ |
Nothing.
msg = "a warning" warningf("this is %s", msg)msg = "a warning" warningf("this is %s", msg)
TRUE value in a logical vectorReturns the index of the first or last TRUE value in a logical vector.
which.first(x, use.names = TRUE) which.last(x, use.names = TRUE)which.first(x, use.names = TRUE) which.last(x, use.names = TRUE)
x |
[ |
use.names |
[ |
[integer(1) | integer(0)].
Returns the index of the first/last TRUE value in x or
an empty integer vector if none is found.
which.first(c(FALSE, TRUE)) which.last(c(FALSE, FALSE))which.first(c(FALSE, TRUE)) which.last(c(FALSE, FALSE))