| Title: | Utility Functions for Open Systems Pharmacology R Packages |
|---|---|
| Description: | A collection of utility functions for R packages in the Open Systems Pharmacology ecosystem. Contains helper functions for working with R6 objects, enumerated lists, and text formatting. Additionally, it provides functions to validate argument inputs. |
| Authors: | Open-Systems-Pharmacology Community [cph, fnd], Michael Sevestre [aut, cre], Pavel Balazki [aut], Juri Solodenko [aut], Indrajeet Patil [aut] (ORCID: <https://orcid.org/0000-0003-1995-6531>, Twitter: @patilindrajeets) |
| Maintainer: | Michael Sevestre <[email protected]> |
| License: | GPL-2 |
| Version: | 1.11.1 |
| Built: | 2026-07-06 12:14:24 UTC |
| Source: | https://github.com/Open-Systems-Pharmacology/OSPSuite.RUtils |
Create Character Option Specification
characterOption( allowedValues = NULL, nullAllowed = FALSE, naAllowed = FALSE, expectedLength = 1 )characterOption( allowedValues = NULL, nullAllowed = FALSE, naAllowed = FALSE, expectedLength = 1 )
allowedValues |
Vector of permitted values. Defaults to |
nullAllowed |
Logical flag indicating whether |
naAllowed |
Logical flag indicating whether |
expectedLength |
Expected length of the option value. Use |
An S3 object of class optionSpec_character and optionSpec.
Format text into cli inline format Allows evaluation of expressions within the text before submitting to logs
cliFormat(..., .envir = parent.frame())cliFormat(..., .envir = parent.frame())
... |
Characters to format |
.envir |
Environment in which to evaluate the expressions |
A formatted character string
Create an enumeration to be used instead of arbitrary values in code. In some languages (C, C++, Python, etc.), enum (or enumeration) is a data type that consists of integer constants and is ideal in contexts where a variable can take on only one of a limited set of possible values (e.g. day of the week). Since R programming language natively doesn't support enumeration, the current function provides a way to create them using lists.
enum(enumValues)enum(enumValues)
enumValues |
A vector or a list of comma-separated constants to use for creating the enum. Optionally, these can be named constants. |
An enumerated list.
Other enumeration-helpers:
enumGetKey(),
enumGetValue(),
enumHasKey(),
enumKeys(),
enumPut(),
enumRemove(),
enumValues()
# Without predefined values Color <- enum(c("Red", "Blue", "Green")) Color myColor <- Color$Red myColor # With predefined values Symbol <- enum(c(Diamond = 1, Triangle = 2, Circle = 2)) Symbol mySymbol <- Symbol$Diamond mySymbol# Without predefined values Color <- enum(c("Red", "Blue", "Green")) Color myColor <- Color$Red myColor # With predefined values Symbol <- enum(c(Diamond = 1, Triangle = 2, Circle = 2)) Symbol mySymbol <- Symbol$Diamond mySymbol
enum
Get the key mapped to the given value in an enum
enumGetKey(enum, value) getEnumKey(enum, value)enumGetKey(enum, value) getEnumKey(enum, value)
enum |
The |
value |
The value that is mapped to the |
Key under which the value is stored. If the value is not in the enum,
NULL is returned.
Other enumeration-helpers:
enum(),
enumGetValue(),
enumHasKey(),
enumKeys(),
enumPut(),
enumRemove(),
enumValues()
Symbol <- enum(c(Diamond = 1, Triangle = 2, Circle = 2)) enumGetKey(Symbol, 1)Symbol <- enum(c(Diamond = 1, Triangle = 2, Circle = 2)) enumGetKey(Symbol, 1)
Return the value that is stored under the given key. If the key is not present, an error is thrown.
enumGetValue(enum, key)enumGetValue(enum, key)
enum |
The |
key |
The |
Value that is assigned to key.
Other enumeration-helpers:
enum(),
enumGetKey(),
enumHasKey(),
enumKeys(),
enumPut(),
enumRemove(),
enumValues()
Symbol <- enum(c(Diamond = 1, Triangle = 2, Circle = 2)) enumGetValue(Symbol, "Diamond")Symbol <- enum(c(Diamond = 1, Triangle = 2, Circle = 2)) enumGetValue(Symbol, "Diamond")
Check if an enum has a certain key.
enumHasKey(key, enum)enumHasKey(key, enum)
key |
Key to check for. |
enum |
Enum where to look for the |
TRUE if a key-value pair for key exists, FALSE otherwise.
Other enumeration-helpers:
enum(),
enumGetKey(),
enumGetValue(),
enumKeys(),
enumPut(),
enumRemove(),
enumValues()
Symbol <- enum(c(Diamond = 1, Triangle = 2, Circle = 2)) enumHasKey("Diamond", Symbol) enumHasKey("Square", Symbol)Symbol <- enum(c(Diamond = 1, Triangle = 2, Circle = 2)) enumHasKey("Diamond", Symbol) enumHasKey("Square", Symbol)
Get all keys of an enum
enumKeys(enum)enumKeys(enum)
enum |
|
List of key names.
Other enumeration-helpers:
enum(),
enumGetKey(),
enumGetValue(),
enumHasKey(),
enumPut(),
enumRemove(),
enumValues()
Symbol <- enum(c(Diamond = 1, Triangle = 2, Circle = 2)) enumKeys(Symbol)Symbol <- enum(c(Diamond = 1, Triangle = 2, Circle = 2)) enumKeys(Symbol)
enum
Add a new key-value pairs to an enum
enumPut(keys, values, enum, overwrite = FALSE)enumPut(keys, values, enum, overwrite = FALSE)
keys |
Keys of the values to be added |
values |
Values to be added |
enum |
The enum to which the specified key-value pairs should be added. WARNING: the original object is not modified! |
overwrite |
If |
Enum with added key-value pair.
Other enumeration-helpers:
enum(),
enumGetKey(),
enumGetValue(),
enumHasKey(),
enumKeys(),
enumRemove(),
enumValues()
myEnum <- enum(c(a = "b")) myEnum <- enumPut("c", "d", myEnum) myEnum <- enumPut(c("c", "d", "g"), c(12, 2, "a"), myEnum, overwrite = TRUE)myEnum <- enum(c(a = "b")) myEnum <- enumPut("c", "d", myEnum) myEnum <- enumPut(c("c", "d", "g"), c(12, 2, "a"), myEnum, overwrite = TRUE)
Remove an entry from the enum.
enumRemove(keys, enum)enumRemove(keys, enum)
keys |
Key(s) of entries to be removed from the enum |
enum |
Enum from which the entries to be removed WARNING: the original object is not modified! |
Enum without the removed entries.
Other enumeration-helpers:
enum(),
enumGetKey(),
enumGetValue(),
enumHasKey(),
enumKeys(),
enumPut(),
enumValues()
Symbol <- enum(c(Diamond = 1, Triangle = 2, Circle = 2)) # either by key enumRemove("Diamond", Symbol) # or by position enumRemove(2L, Symbol)Symbol <- enum(c(Diamond = 1, Triangle = 2, Circle = 2)) # either by key enumRemove("Diamond", Symbol) # or by position enumRemove(2L, Symbol)
Get the values stored in an enum
enumValues(enum)enumValues(enum)
enum |
|
List of values stored in the enum.
Other enumeration-helpers:
enum(),
enumGetKey(),
enumGetValue(),
enumHasKey(),
enumKeys(),
enumPut(),
enumRemove()
Symbol <- enum(c(Diamond = 1, Triangle = 2, Circle = 2)) enumValues(Symbol)Symbol <- enum(c(Diamond = 1, Triangle = 2, Circle = 2)) enumValues(Symbol)
Flatten a list to an atomic vector of desired type
flattenList(x, type)flattenList(x, type)
x |
A list or an atomic vector. If the latter, no change will be made. |
type |
Type of atomic vector to be returned. |
The type argument will decide which variant from purrr::flatten() family
is used to flatten the list.
An atomic vector of desired type.
flattenList(list(1, 2, 3, NA), type = "numeric") flattenList(list(TRUE, FALSE, NA), type = "integer")flattenList(list(1, 2, 3, NA), type = "numeric") flattenList(list(TRUE, FALSE, NA), type = "integer")
Calculates x / y while substituting values below epsilon (for x and y) by epsilon.
x and y must be of the same length
foldSafe(x, y, epsilon = ospsuiteUtilsEnv$LOG_SAFE_EPSILON)foldSafe(x, y, epsilon = ospsuiteUtilsEnv$LOG_SAFE_EPSILON)
x |
A numeric or a vector of numerics. |
y |
A numeric or a vector of numerics. |
epsilon |
A very small number which is considered as threshold below which
all values are treated as |
A vector with x / y.
inputX <- c(NA, 1, 5, 0, -1) inputY <- c(1, -1, NA, 0, -1) folds <- foldSafe(inputX, inputY)inputX <- c(NA, 1, 5, 0, -1) inputY <- c(1, -1, NA, 0, -1) folds <- foldSafe(inputX, inputY)
Render numeric values of an object as character using the specified format:
If object is a data.frame or a list, formatNumerics applies on each of its fields
If object is of type character or integer, formatNumerics renders the values as is
If object is of type numeric, formatNumerics applies the defined format
formatNumerics( object, digits = ospsuiteUtilsEnv$formatNumericsDigits, scientific = FALSE )formatNumerics( object, digits = ospsuiteUtilsEnv$formatNumericsDigits, scientific = FALSE )
object |
An R object such as a list, a data.frame, character or numeric values. |
digits |
Number of decimal digits to render |
scientific |
Logical value defining if scientific writing is rendered |
Numeric values are rendered as character values. If object is a
data.frame or a list, a data.frame or list is returned with numeric values
rendered as character values.
# Format array of numeric values formatNumerics(log(c(12, 15, 0.3)), digits = 1, scientific = TRUE) # Format a data.frame x <- data.frame(parameter = c("a", "b", "c"), value = c(1, 110.4, 6.666)) formatNumerics(x, digits = 2, scientific = FALSE)# Format array of numeric values formatNumerics(log(c(12, 15, 0.3)), digits = 1, scientific = TRUE) # Format a data.frame x <- data.frame(parameter = c("a", "b", "c"), value = c(1, 110.4, 6.666)) formatNumerics(x, digits = 2, scientific = FALSE)
Get current log folder where logs are saved
getLogFolder()getLogFolder()
## Not run: # Set/get log folder to a temporary directory setLogFolder(tempdir()) getLogFolder() # Set/get logFolder to `NULL`, cancel saving of logs setLogFolder() getLogFolder() ## End(Not run)## Not run: # Set/get log folder to a temporary directory setLogFolder(tempdir()) getLogFolder() # Set/get logFolder to `NULL`, cancel saving of logs setLogFolder() getLogFolder() ## End(Not run)
{ospsuite.utils} package setting.Get the value of a global {ospsuite.utils} package setting.
getOSPSuiteUtilsSetting(settingName)getOSPSuiteUtilsSetting(settingName)
settingName |
String name of the setting |
Value of the setting stored in ospsuiteEnv. If the setting does not exist,
an error is thrown.
getOSPSuiteUtilsSetting("packageName") getOSPSuiteUtilsSetting("suiteName") getOSPSuiteUtilsSetting("formatNumericsDigits")getOSPSuiteUtilsSetting("packageName") getOSPSuiteUtilsSetting("suiteName") getOSPSuiteUtilsSetting("formatNumericsDigits")
Validate that no empty string is present
hasEmptyStrings(x) validateHasOnlyNonEmptyStrings(x)hasEmptyStrings(x) validateHasOnlyNonEmptyStrings(x)
x |
A character string or a vector of character strings. |
If any of the following conditions are met, the input string is considered empty:
if any NAs are present (e.g. x = c("a", "abc", NA))
if string is empty (e.g. x = list("a", "abc", ""))
if length is 0 (e.g. x = character())
hasEmptyStrings() returns TRUE if any of the strings are empty; FALSE
otherwise.
validateHasOnlyNonEmptyStrings() produces an error if empty string are
present. It returns NULL otherwise.
hasEmptyStrings(c("x", "y")) # FALSE hasEmptyStrings(list("x", "y")) # FALSE hasEmptyStrings(" abc ") # FALSE hasEmptyStrings(c("", "y")) # TRUE hasEmptyStrings(list("", "y")) # TRUE hasEmptyStrings(NA) # TRUE hasEmptyStrings(character(0)) # TRUE hasEmptyStrings(c(NA, "x", "y")) # TRUE validateHasOnlyNonEmptyStrings(c("x", "y")) # NULL validateHasOnlyNonEmptyStrings(list("x", "y")) # NULL validateHasOnlyNonEmptyStrings(" abc ") # NULL # validateHasOnlyNonEmptyStrings(c("", "y")) # error # validateHasOnlyNonEmptyStrings(list("", "y")) # error # validateHasOnlyNonEmptyStrings(NA) # error # validateHasOnlyNonEmptyStrings(character(0)) # error # validateHasOnlyNonEmptyStrings(c(NA, "x", "y")) # errorhasEmptyStrings(c("x", "y")) # FALSE hasEmptyStrings(list("x", "y")) # FALSE hasEmptyStrings(" abc ") # FALSE hasEmptyStrings(c("", "y")) # TRUE hasEmptyStrings(list("", "y")) # TRUE hasEmptyStrings(NA) # TRUE hasEmptyStrings(character(0)) # TRUE hasEmptyStrings(c(NA, "x", "y")) # TRUE validateHasOnlyNonEmptyStrings(c("x", "y")) # NULL validateHasOnlyNonEmptyStrings(list("x", "y")) # NULL validateHasOnlyNonEmptyStrings(" abc ") # NULL # validateHasOnlyNonEmptyStrings(c("", "y")) # error # validateHasOnlyNonEmptyStrings(list("", "y")) # error # validateHasOnlyNonEmptyStrings(NA) # error # validateHasOnlyNonEmptyStrings(character(0)) # error # validateHasOnlyNonEmptyStrings(c(NA, "x", "y")) # error
Validate that a vector has only unique values
hasOnlyDistinctValues(values, na.rm = TRUE) validateHasOnlyDistinctValues(values, na.rm = TRUE)hasOnlyDistinctValues(values, na.rm = TRUE) validateHasOnlyDistinctValues(values, na.rm = TRUE)
values |
An array of values |
na.rm |
Logical to decide if missing values should be removed from the
duplicate checking. Note that duplicate |
hasOnlyDistinctValues returns TRUE if all values are unique.
validateHasOnlyDistinctValues() returns NULL if only unique values
present, otherwise produces error.
hasOnlyDistinctValues(c("x", "y")) hasOnlyDistinctValues(c("x", "y", "x")) hasOnlyDistinctValues(c("x", NA, "y", NA), na.rm = FALSE) hasOnlyDistinctValues(c("x", NA, "y", NA), na.rm = TRUE) validateHasOnlyDistinctValues(c("x", "y")) # NULL # validateHasOnlyDistinctValues(c("x", "y", "x")) # errorhasOnlyDistinctValues(c("x", "y")) hasOnlyDistinctValues(c("x", "y", "x")) hasOnlyDistinctValues(c("x", NA, "y", NA), na.rm = FALSE) hasOnlyDistinctValues(c("x", NA, "y", NA), na.rm = TRUE) validateHasOnlyDistinctValues(c("x", "y")) # NULL # validateHasOnlyDistinctValues(c("x", "y", "x")) # error
Short-key checking if arguments 1 and 2 are equal, output argument 3 if equal, or output argument 4 otherwise.
ifEqual(x, y, outputIfEqual, outputIfNotEqual = NULL)ifEqual(x, y, outputIfEqual, outputIfNotEqual = NULL)
x |
argument 1 |
y |
argument 2 |
outputIfEqual |
argument 3 |
outputIfNotEqual |
argument 4 |
ifEqual(1, 1, "x", "y") # "x" ifEqual(1, 2, "x", "y") # "y"ifEqual(1, 1, "x", "y") # "x" ifEqual(1, 2, "x", "y") # "y"
Shortkey checking if arguments 1 is included in 2, output argument 3 if included, or output argument 4 otherwise.
ifIncluded(x, y, outputIfIncluded, outputIfNotIncluded = NULL)ifIncluded(x, y, outputIfIncluded, outputIfNotIncluded = NULL)
x |
argument 1 |
y |
argument 2 |
outputIfIncluded |
argument 3 |
outputIfNotIncluded |
argument 4 |
ifIncluded("a", c("a", "b"), 1, 2) # 1 ifIncluded("x", c("a", "b"), 1, 2) # 2ifIncluded("a", c("a", "b"), 1, 2) # 1 ifIncluded("x", c("a", "b"), 1, 2) # 2
NULL
Short-key checking if argument 1 is not NULL, output the argument 2 if not
null, or output argument 3 otherwise.
Check if condition is not NULL, if so output outputIfNotNull,
otherwise, output outputIfNull.
ifNotNull(condition, outputIfNotNull, outputIfNull = NULL)ifNotNull(condition, outputIfNotNull, outputIfNull = NULL)
condition |
argument 1 |
outputIfNotNull |
argument 2 |
outputIfNull |
argument 3 |
outputIfNotNull if condition is not NULL, outputIfNull otherwise.
ifNotNull(NULL, "x") ifNotNull(NULL, "x", "y") ifNotNull(1 < 2, "x", "y")ifNotNull(NULL, "x") ifNotNull(NULL, "x", "y") ifNotNull(1 < 2, "x", "y")
Create Integer Option Specification
integerOption( min = -Inf, max = Inf, nullAllowed = FALSE, naAllowed = FALSE, expectedLength = 1 )integerOption( min = -Inf, max = Inf, nullAllowed = FALSE, naAllowed = FALSE, expectedLength = 1 )
min |
Minimum allowed value. Defaults to |
max |
Maximum allowed value. Defaults to |
nullAllowed |
Logical flag indicating whether |
naAllowed |
Logical flag indicating whether |
expectedLength |
Expected length of the option value. Use |
An S3 object of class optionSpec_integer and optionSpec.
Validate if the provided object is empty
isEmpty(object) validateIsNotEmpty(object)isEmpty(object) validateIsNotEmpty(object)
object |
An object or an atomic vector or a list of objects. |
isEmpty() returns TRUE if the object is empty; FALSE otherwise.
validateIsNotEmpty() returns NULL if validation is successful.
Otherwise, error is signaled.
# empty list or data.frame isEmpty(NULL) isEmpty(numeric()) isEmpty(list()) isEmpty(data.frame()) # accounts for filtering of arrays and data.frame df <- data.frame(x = c(1, 2, 3), y = c(4, 5, 6)) isEmpty(df) isEmpty(df$x[FALSE]) isEmpty(df[FALSE, ]) # validation helper validateIsNotEmpty(list(1, 2)) # NULL # validateIsNotEmpty(NULL) # error# empty list or data.frame isEmpty(NULL) isEmpty(numeric()) isEmpty(list()) isEmpty(data.frame()) # accounts for filtering of arrays and data.frame df <- data.frame(x = c(1, 2, 3), y = c(4, 5, 6)) isEmpty(df) isEmpty(df$x[FALSE]) isEmpty(df[FALSE, ]) # validation helper validateIsNotEmpty(list(1, 2)) # NULL # validateIsNotEmpty(NULL) # error
Validate if the provided path has required extension
isFileExtension(file, extension) validateIsFileExtension(file, extension)isFileExtension(file, extension) validateIsFileExtension(file, extension)
file |
A name of the file or full path. |
extension |
A required extension of the file. |
isFileExtension() returns TRUE if the file name (or full path) includes
the extension.
If validations are successful, validateIsFileExtension() returns NULL.
Otherwise, error is signaled.
isFileExtension("enum.R", "R") # TRUE isFileExtension("enum.R", "pkml") # FALSE validateIsFileExtension("enum.R", "R") # NULL # validateIsFileExtension("enum.R", "pkml") # errorisFileExtension("enum.R", "R") # TRUE isFileExtension("enum.R", "pkml") # FALSE validateIsFileExtension("enum.R", "R") # NULL # validateIsFileExtension("enum.R", "pkml") # error
Assess if a file is UTF-8 encoded.
isFileUTF8(file)isFileUTF8(file)
file |
A name of the file or full path. |
A logical assessing whether there is non UTF-8 encoded characters in file
writeLines(c("Hello, world!"), "utf.txt") writeLines(c("Hello, world!", "\xb5g/L"), "non-utf.txt") isFileUTF8("utf.txt") # TRUE isFileUTF8("non-utf.txt") # FALSEwriteLines(c("Hello, world!"), "utf.txt") writeLines(c("Hello, world!", "\xb5g/L"), "non-utf.txt") isFileUTF8("utf.txt") # TRUE isFileUTF8("non-utf.txt") # FALSE
Check if a vector of values is included in another vector of values
isIncluded(values, parentValues) validateIsIncluded(values, parentValues, nullAllowed = FALSE)isIncluded(values, parentValues) validateIsIncluded(values, parentValues, nullAllowed = FALSE)
values |
A vector of values. |
parentValues |
A vector of values where |
nullAllowed |
Boolean flag if |
isIncluded() returns TRUE if the value or all values (if it's a
vector) are present in the parentValues; FALSE otherwise.
validateIsIncluded() returns NULL if child value is included in parent
value set, otherwise error is signaled.
# check if a column is present in dataframe A <- data.frame( col1 = c(1, 2, 3), col2 = c(4, 5, 6), col3 = c(7, 8, 9) ) isIncluded("col3", names(A)) # TRUE # check if single element is present in a vector (atomic or non-atomic) isIncluded("x", list("w", "x", 1, 2)) # TRUE isIncluded("x", c("w", "a", "y")) # FALSE # check if **all** values (if it's a vector) are contained in parent values isIncluded(c("x", "y"), c("a", "y", "b", "x")) # TRUE isIncluded(list("x", 1), list("a", "b", "x", 1)) # TRUE isIncluded(c("x", "y"), c("a", "b", "x")) # FALSE isIncluded(list("x", 1), list("a", "b", "x")) # FALSE # corresponding validation validateIsIncluded("col3", names(A)) # NULL # validateIsIncluded("col6", names(A)) # error# check if a column is present in dataframe A <- data.frame( col1 = c(1, 2, 3), col2 = c(4, 5, 6), col3 = c(7, 8, 9) ) isIncluded("col3", names(A)) # TRUE # check if single element is present in a vector (atomic or non-atomic) isIncluded("x", list("w", "x", 1, 2)) # TRUE isIncluded("x", c("w", "a", "y")) # FALSE # check if **all** values (if it's a vector) are contained in parent values isIncluded(c("x", "y"), c("a", "y", "b", "x")) # TRUE isIncluded(list("x", 1), list("a", "b", "x", 1)) # TRUE isIncluded(c("x", "y"), c("a", "b", "x")) # FALSE isIncluded(list("x", 1), list("a", "b", "x")) # FALSE # corresponding validation validateIsIncluded("col3", names(A)) # NULL # validateIsIncluded("col6", names(A)) # error
Check if the provided object has expected length
isOfLength(object, nbElements) validateIsOfLength(object, nbElements)isOfLength(object, nbElements) validateIsOfLength(object, nbElements)
object |
An object or a list of objects |
nbElements |
number of elements that are supposed in object |
isOfLength() returns TRUE if the object or all objects inside the list
have nbElements.
For validateIsOfLength(), if validations are successful, NULL is
returned. Otherwise, error is signaled.
Only the first level of the given list is considered.
df <- data.frame(x = c(1, 2, 3)) isOfLength(df, 1) # TRUE isOfLength(df, 3) # FALSE validateIsOfLength(list(1, 2), 2L) # NULL # validateIsOfLength(c("3", "4"), 3L) # errordf <- data.frame(x = c(1, 2, 3)) isOfLength(df, 1) # TRUE isOfLength(df, 3) # FALSE validateIsOfLength(list(1, 2), 2L) # NULL # validateIsOfLength(c("3", "4"), 3L) # error
Check if the provided object is of certain type
isOfType(object, type, nullAllowed = FALSE)isOfType(object, type, nullAllowed = FALSE)
object |
An object or an atomic vector or a list of objects. |
type |
A single string or a vector of string representation or class of the type that should be checked for. |
nullAllowed |
Boolean flag if |
TRUE if the object or all objects inside the list are of the given type.
Only the first level of the given list is considered.
# checking type of a single object df <- data.frame(x = c(1, 2, 3)) isOfType(df, "data.frame")# checking type of a single object df <- data.frame(x = c(1, 2, 3)) isOfType(df, "data.frame")
Relative paths will be detected based on the presence of wildcard character(*) in the path specification.
isPathAbsolute(path) validateIsPathAbsolute(path) validatePathIsAbsolute(path)isPathAbsolute(path) validateIsPathAbsolute(path) validatePathIsAbsolute(path)
path |
A valid file path name. |
isPathAbsolute() returns TRUE if path is absolute (no wildcard); FALSE otherwise.
validateIsPathAbsolute() returns NULL if path is absolute. Otherwise, error is signaled.
# check if path is absolute isPathAbsolute("Organism|path") # TRUE isPathAbsolute("Organism|*path") # FALSE # validation: no error if path is absolute validateIsPathAbsolute("Organism|path") # validation: error otherwise # validateIsPathAbsolute("Organism|*path")# check if path is absolute isPathAbsolute("Organism|path") # TRUE isPathAbsolute("Organism|*path") # FALSE # validation: no error if path is absolute validateIsPathAbsolute("Organism|path") # validation: error otherwise # validateIsPathAbsolute("Organism|*path")
Validate if objects are of same length
isSameLength(...) validateIsSameLength(...)isSameLength(...) validateIsSameLength(...)
... |
Objects to compare. |
isSameLength() returns TRUE if all objects have same lengths.
For validateIsSameLength(), if validations are successful, NULL is
returned. Otherwise, error is signaled.
# compare length of only 2 objects isSameLength(mtcars, ToothGrowth) # FALSE isSameLength(cars, BOD) # TRUE # or more number of objects isSameLength(c(1, 2), c(TRUE, FALSE), c("x", "y")) # TRUE isSameLength(list(1, 2), list(TRUE, FALSE), list("x")) # FALSE # validation validateIsSameLength(list(1, 2), c("3", "4")) # NULL # validateIsSameLength(list(1, 2), c("3", "4"), c(FALSE)) # error# compare length of only 2 objects isSameLength(mtcars, ToothGrowth) # FALSE isSameLength(cars, BOD) # TRUE # or more number of objects isSameLength(c(1, 2), c(TRUE, FALSE), c("x", "y")) # TRUE isSameLength(list(1, 2), list(TRUE, FALSE), list("x")) # FALSE # validation validateIsSameLength(list(1, 2), c("3", "4")) # NULL # validateIsSameLength(list(1, 2), c("3", "4"), c(FALSE)) # error
Assess if a character vector is UTF-8 encoded.
isUTF8(text)isUTF8(text)
text |
A character vector |
A logical assessing whether there is non UTF-8 encoded characters in text
isUTF8("Hello, world!") # TRUE isUTF8("\xb5g/L") # FALSEisUTF8("Hello, world!") # TRUE isUTF8("\xb5g/L") # FALSE
Catch errors, log and display meaningful information
logCatch(expr)logCatch(expr)
expr |
Evaluated code chunks |
# Catch and display warning message logCatch({ warning("This is a warning message") })# Catch and display warning message logCatch({ warning("This is a warning message") })
Log debug with time stamp
logDebug(msg)logDebug(msg)
msg |
Character values of message to log that leverages |
# Log debug logDebug("This is a debugging message")# Log debug logDebug("This is a debugging message")
Log error with time stamp
logError(msg)logError(msg)
msg |
Character values of message to log that leverages |
# Log error logError(cliFormat("This is an {.strong error} message")) # Log error with indications logError(cliFormat( "This is an {.strong error} message", "Check these {.val values} or this {.fn function}" ))# Log error logError(cliFormat("This is an {.strong error} message")) # Log error with indications logError(cliFormat( "This is an {.strong error} message", "Check these {.val values} or this {.fn function}" ))
Create Logical Option Specification
logicalOption(nullAllowed = FALSE, naAllowed = FALSE, expectedLength = 1)logicalOption(nullAllowed = FALSE, naAllowed = FALSE, expectedLength = 1)
nullAllowed |
Logical flag indicating whether |
naAllowed |
Logical flag indicating whether |
expectedLength |
Expected length of the option value. Use |
An S3 object of class optionSpec_logical and optionSpec.
Log information with time stamp accounting for message type.
Message type will point toward the most appropriate cli function display.
logInfo(msg, type = "info")logInfo(msg, type = "info")
msg |
Character values of message to log that leverages |
type |
Name of the message type to toward best
|
# Log information logInfo(cliFormat("This is an {.strong info} message")) # Log a title logInfo(cliFormat("Task: {.strong tic toc test}"), type = "h1") # Log success t0 <- tic() Sys.sleep(3) logInfo(cliFormat("Task: {.strong tic toc test} completed [{toc(t0, \"s\")}]"), type = "success")# Log information logInfo(cliFormat("This is an {.strong info} message")) # Log a title logInfo(cliFormat("Task: {.strong tic toc test}"), type = "h1") # Log success t0 <- tic() Sys.sleep(3) logInfo(cliFormat("Task: {.strong tic toc test} completed [{toc(t0, \"s\")}]"), type = "success")
epsilon by epsilon.Computes logarithm of a number or of a vector of numbers and handles zeros while
substituting all values below epsilon by epsilon.
logSafe(x, base = exp(1), epsilon = ospsuiteUtilsEnv$LOG_SAFE_EPSILON)logSafe(x, base = exp(1), epsilon = ospsuiteUtilsEnv$LOG_SAFE_EPSILON)
x |
A numeric or a vector of numerics. |
base |
a positive or complex number: the base with respect to which logarithms are computed. Defaults to e = exp(1). |
epsilon |
A very small number which is considered as threshold below which
all values are treated as |
log(x, base = base) for x > epsilon, or log(epsilon, base = base),
or NA_real_ for NA elements.
inputVector <- c(NA, 1, 5, 0, -1) logSafe(inputVector)inputVector <- c(NA, 1, 5, 0, -1) logSafe(inputVector)
Log warning with time stamp
logWarning(msg)logWarning(msg)
msg |
Character values of message to log that leverages |
# Log warning logWarning(cliFormat("This is a {.strong warning} message"))# Log warning logWarning(cliFormat("This is a {.strong warning} message"))
Most of these messages will be relevant only in the context of OSP R package ecosystem.
messagesmessages
An object of class list of length 47.
A string with error message.
# example with string messages$errorEnumNotAllNames # example with function messages$errorPropertyReadOnly("age") # example display with warning warning(messages$errorPropertyReadOnly("age")) # example display using logs logInfo(messages$errorPropertyReadOnly("age"))# example with string messages$errorEnumNotAllNames # example with function messages$errorPropertyReadOnly("age") # example display with warning warning(messages$errorPropertyReadOnly("age")) # example display using logs logInfo(messages$errorPropertyReadOnly("age"))
Create Numeric Option Specification
numericOption( min = -Inf, max = Inf, nullAllowed = FALSE, naAllowed = FALSE, expectedLength = 1 )numericOption( min = -Inf, max = Inf, nullAllowed = FALSE, naAllowed = FALSE, expectedLength = 1 )
min |
Minimum allowed value. Defaults to |
max |
Maximum allowed value. Defaults to |
nullAllowed |
Logical flag indicating whether |
naAllowed |
Logical flag indicating whether |
expectedLength |
Expected length of the option value. Use |
An S3 object of class optionSpec_numeric and optionSpec.
Count number of objects
objectCount(x)objectCount(x)
x |
An object (an atomic vector, a list, or instance(s) of a class). |
Classes in R can roughly be distinguished as following:
Vector-style classes have the property that length() represents number of
elements (e.g., factor, list, etc.).
Record-style (or dataframe or scalar) classes, on the other hand, have
complex structures to represent a single thing (e.g., data.frame, R6,
lm, etc.).
This function counts objects differently depending on the entered class:
If the argument is a vector or a vector-style class, it will return the
output from length() function. Otherwise, it will returns 1.
For example,
length(mtcars) returns 11, but objectCount(mtcars) will
return 1, while
length(list(1, 2)) returns 2, and objectCount(list(1, 2)) will return
2 as well.
Integer representing the count of objects.
# vectors or vector-style classes objectCount(c(1, 2, 3)) # 3 objectCount(list("a", "b")) # 2 objectCount(list(iris, mtcars)) # 2 # everything else objectCount(mtcars) # 1 objectCount(lm(wt ~ mpg, mtcars)) # 1 objectCount(new.env()) # 1# vectors or vector-style classes objectCount(c(1, 2, 3)) # 3 objectCount(list("a", "b")) # 2 objectCount(list(iris, mtcars)) # 2 # everything else objectCount(mtcars) # 1 objectCount(lm(wt ~ mpg, mtcars)) # 1 objectCount(new.env()) # 1
Prints the class name of an object with nice formatting using cli.
ospPrintClass(x)ospPrintClass(x)
x |
An R object |
Invisibly returns the input object
Other print functions:
ospPrintHeader(),
ospPrintItems()
# Print class name of a data frame ospPrintClass(iris)# Print class name of a data frame ospPrintClass(iris)
Prints a header with the specified level (H1, H2, or H3) using cli.
ospPrintHeader(text, level = 1)ospPrintHeader(text, level = 1)
text |
The text to print as a header |
level |
The header level (1, 2, or 3) |
Invisibly returns NULL
Other print functions:
ospPrintClass(),
ospPrintItems()
# Print different header levels ospPrintHeader("Main Title", 1) ospPrintHeader("Section Title", 2) ospPrintHeader("Subsection Title", 3)# Print different header levels ospPrintHeader("Main Title", 1) ospPrintHeader("Section Title", 2) ospPrintHeader("Subsection Title", 3)
Prints a list of items from a vector or list, with an optional title. Items are indented and prefixed with a dash.
ospPrintItems(x, title = NULL, print_empty = FALSE)ospPrintItems(x, title = NULL, print_empty = FALSE)
x |
A vector or list |
title |
Optional title to display before the list (default: NULL) |
print_empty |
Whether to print empty values (NULL, NA, empty string) (default: FALSE) |
Invisibly returns the input object
Other print functions:
ospPrintClass(),
ospPrintHeader()
# Print a simple vector with title vector <- c("A", "B", "C") ospPrintItems(vector, title = "Letters") # Print a named vector with title named_vector <- c(A = 1, B = 2, C = 3) ospPrintItems(named_vector, title = "Letters") # Print a list including empty values list_with_nulls <- list("Min" = NULL, "Max" = 100, "Unit" = NA) ospPrintItems(list_with_nulls, title = "Parameters", print_empty = TRUE)# Print a simple vector with title vector <- c("A", "B", "C") ospPrintItems(vector, title = "Letters") # Print a named vector with title named_vector <- c(A = 1, B = 2, C = 3) ospPrintItems(named_vector, title = "Letters") # Print a list including empty values list_with_nulls <- list("Min" = NULL, "Max" = 100, "Unit" = NA) ospPrintItems(list_with_nulls, title = "Parameters", print_empty = TRUE)
ospsuiteEnv. Can be used with
getOSPSuiteUtilsSetting()
Names of the settings stored in ospsuiteEnv. Can be used with
getOSPSuiteUtilsSetting()
ospsuiteUtilsSettingNamesospsuiteUtilsSettingNames
An object of class list of length 5.
ospsuiteUtilsSettingNamesospsuiteUtilsSettingNames
Base class that implements some basic properties for printing to console.
new()
Create a new Printable object.
Printable$new()
clone()
The objects of this class are cloneable with this method.
Printable$clone(deep = FALSE)
deepWhether to make a deep clone.
myPrintable <- R6::R6Class( "myPrintable", inherit = Printable, public = list( x = NULL, y = NULL, print = function() { private$printClass() private$printLine("x", self$x) private$printLine("y", self$y) invisible(self) } ) ) x <- myPrintable$new() xmyPrintable <- R6::R6Class( "myPrintable", inherit = Printable, public = list( x = NULL, y = NULL, print = function() { private$printClass() private$printLine("x", self$x) private$printLine("y", self$y) invisible(self) } ) ) x <- myPrintable$new() x
Mask error trace messages
setErrorMasking(patterns)setErrorMasking(patterns)
patterns |
Character patterns to identify with |
## Not run: setErrorMasking(c("tryCatch", "withCallingHandlers")) ## End(Not run)## Not run: setErrorMasking(c("tryCatch", "withCallingHandlers")) ## End(Not run)
Mask info messages
setInfoMasking(patterns)setInfoMasking(patterns)
patterns |
Character patterns to identify with |
## Not run: # Mask ggplot2 message when line is used with 1 value per group setInfoMasking("Each group consists of only one observation") ## End(Not run)## Not run: # Mask ggplot2 message when line is used with 1 value per group setInfoMasking("Each group consists of only one observation") ## End(Not run)
Initialize logs and their settings
setLogFolder(logFolder = NULL)setLogFolder(logFolder = NULL)
logFolder |
Optional folder path to save log file |
Mask warning messages
setWarningMasking(patterns)setWarningMasking(patterns)
patterns |
Character patterns to identify with |
## Not run: # Mask ggplot2 warning message when missing values are found setWarningMasking("rows containing missing values") ## End(Not run)## Not run: # Mask ggplot2 warning message when missing values are found setWarningMasking("rows containing missing values") ## End(Not run)
Print time stamp
timeStamp()timeStamp()
timeStamp()timeStamp()
Get elapsed time between tic trigger and now
toc(tic, unit = "min")toc(tic, unit = "min")
tic |
Start time |
unit |
display unit of elapsed time |
Character displaying elapsed time in unit
t0 <- tic() Sys.sleep(2) # Get elapsed time in seconds toc(t0, "s") # Get elapsed time in minutes toc(t0, "min")t0 <- tic() Sys.sleep(2) # Get elapsed time in seconds toc(t0, "s") # Get elapsed time in minutes toc(t0, "min")
Make sure the object is a list
toList(object)toList(object)
object |
Object to be converted to a list. |
If is.list(object) == TRUE, returns the object; otherwise, list(object).
toList(list("a" = 1, "b" = 2)) toList(c("a" = 1, "b" = 2))toList(list("a" = 1, "b" = 2)) toList(c("a" = 1, "b" = 2))
NA of desired typeConvert special constants to NA of desired type
toMissingOfType(x, type)toMissingOfType(x, type)
x |
A single element. |
type |
Type of atomic vector to be returned. |
Special constants (NULL, Inf, -Inf, NaN, NA) will be converted to
NA of desired type.
This function is not vectorized, and therefore only scalar values should be entered.
toMissingOfType(NA, type = "real") toMissingOfType(NULL, type = "integer")toMissingOfType(NA, type = "real") toMissingOfType(NULL, type = "integer")
value is in the given enum. If not, stops with an error.Check if value is in the given enum. If not, stops with an error.
validateEnumValue(value, enum, nullAllowed = FALSE)validateEnumValue(value, enum, nullAllowed = FALSE)
value |
A value to search for in the |
enum |
|
nullAllowed |
If |
Symbol <- enum(c(Diamond = 1, Triangle = 2, Circle = 2)) validateEnumValue(1, Symbol)Symbol <- enum(c(Diamond = 1, Triangle = 2, Circle = 2)) validateEnumValue(1, Symbol)
Validate if a file is UTF-8 encoded.
validateIsFileUTF8(file)validateIsFileUTF8(file)
file |
A name of the file or full path. |
If validations are successful, validateIsFileUTF8() returns NULL.
Otherwise, error is signaled.
writeLines(c("Hello, world!"), "utf.txt") writeLines(c("Hello, world!", "\xb5g/L"), "non-utf.txt") validateIsFileUTF8("utf.txt") # NULL ## Not run: validateIsFileUTF8("non-utf.txt") # Error ## End(Not run)writeLines(c("Hello, world!"), "utf.txt") writeLines(c("Hello, world!", "\xb5g/L"), "non-utf.txt") validateIsFileUTF8("utf.txt") # NULL ## Not run: validateIsFileUTF8("non-utf.txt") # Error ## End(Not run)
Check if the provided object is of certain type. If not, stop with an error.
validateIsOfType(object, type, nullAllowed = FALSE) validateIsCharacter(object, nullAllowed = FALSE) validateIsString(object, nullAllowed = FALSE) validateIsNumeric(object, nullAllowed = FALSE) validateIsInteger(object, nullAllowed = FALSE) validateIsLogical(object, nullAllowed = FALSE)validateIsOfType(object, type, nullAllowed = FALSE) validateIsCharacter(object, nullAllowed = FALSE) validateIsString(object, nullAllowed = FALSE) validateIsNumeric(object, nullAllowed = FALSE) validateIsInteger(object, nullAllowed = FALSE) validateIsLogical(object, nullAllowed = FALSE)
object |
An object or an atomic vector or a list of objects. |
type |
A single string or a vector of string representation or class of the type that should be checked for. |
nullAllowed |
Boolean flag if |
NULL if the entered object is of expected type, otherwise produces error.
Also accepts NULL as an input if nullAllowed argument is set to TRUE.
A <- data.frame( col1 = c(1, 2, 3), col2 = c(4, 5, 6), col3 = c(7, 8, 9) ) validateIsOfType(A, "data.frame") validateIsInteger(5) validateIsNumeric(1.2) validateIsCharacter("x") validateIsLogical(TRUE)A <- data.frame( col1 = c(1, 2, 3), col2 = c(4, 5, 6), col3 = c(7, 8, 9) ) validateIsOfType(A, "data.frame") validateIsInteger(5) validateIsNumeric(1.2) validateIsCharacter("x") validateIsLogical(TRUE)
Validates a list of options against specified validation rules. Supports both
modern spec constructors (integerOption(), etc.) and legacy list format for
backward compatibility.
validateIsOption(options, validOptions)validateIsOption(options, validOptions)
options |
A list of options to validate. |
validOptions |
A list specifying validation rules for each option. Each entry should either be:
|
Each entry in validOptions is validated against the matching value
from options. Spec objects created with constructors (e.g.,
integerOption()) are recommended because they express intent clearly and
work well with IDEs. For backward compatibility, legacy list-based specs
are still accepted and are automatically normalized to optionSpec before
validation.
Returns NULL invisibly if all validations pass. Stops with detailed
error message listing all failures if any validation fails.
validOptions <- list( maxIterations = integerOption(min = 1L, max = 10000L), method = characterOption(allowedValues = c("a", "b")), threshold = numericOption(min = 0, max = 1, nullAllowed = TRUE) ) options <- list(maxIterations = 100L, method = "a", threshold = 0.05) validateIsOption(options, validOptions)validOptions <- list( maxIterations = integerOption(min = 1L, max = 10000L), method = characterOption(allowedValues = c("a", "b")), threshold = numericOption(min = 0, max = 1, nullAllowed = TRUE) ) options <- list(maxIterations = 100L, method = "a", threshold = 0.05) validateIsOption(options, validOptions)
Validates a vector x based on specified criteria, including type correctness, value range,
allowed values, and handling of NULL and NA values. If the vector fails any validation,
an informative error message is thrown.
validateVector( x, type = NULL, valueRange = NULL, allowedValues = NULL, nullAllowed = FALSE, naAllowed = FALSE ) validateVectorRange(x, type, valueRange) validateVectorValues(x, type, allowedValues = NULL, naAllowed = FALSE)validateVector( x, type = NULL, valueRange = NULL, allowedValues = NULL, nullAllowed = FALSE, naAllowed = FALSE ) validateVectorRange(x, type, valueRange) validateVectorValues(x, type, allowedValues = NULL, naAllowed = FALSE)
x |
Vector to validate. |
type |
Expected type of elements in |
valueRange |
Optional vector of length 2 specifying the range of allowed values
for |
allowedValues |
Optional vector specifying a set of allowed values for |
nullAllowed |
Logical flag indicating whether |
naAllowed |
Logical flag indicating whether elements in |
validateVector is the primary function for checking a vector against defined validation criteria.
It ensures that x meets the type, range, and allowed value conditions specified. For more detailed
validations related to the value range and allowed values, validateVectorRange and
validateVectorValues functions are utilized respectively.
Does not return a value explicitly but will stop with a descriptive error message if any of the validations fail.
validateVector(x = 1:5, type = "integer") validateVector(x = c(1.2, 2.5), type = "numeric", valueRange = c(1, 3)) validateVector(x = c("a", "b"), type = "character", allowedValues = c("a", "b", "c")) validateVector( x = as.Date("2020-01-01"), type = "Date", valueRange = as.Date(c("2020-01-01", "2020-12-31")) ) # Range validation examples validateVectorRange(x = c(5, 10), type = "numeric", valueRange = c(1, 10)) validateVectorRange(x = c("a", "b"), type = "character", valueRange = c("a", "c")) validateVectorRange( x = as.Date(c("2020-01-01")), type = "Date", valueRange = as.Date(c("2020-01-01", "2020-12-31")) ) validateVectorRange(x = 1:3, type = "integer", valueRange = c(1L, 5L)) # Allowed values validation examples validateVectorValues(x = c("a", "b"), type = "character", allowedValues = c("a", "b", "c")) validateVectorValues(x = c(2L, 4L), type = "integer", allowedValues = c(1L, 2L, 3L, 4L)) validateVectorValues(x = c(TRUE), type = "logical", allowedValues = c(TRUE, FALSE))validateVector(x = 1:5, type = "integer") validateVector(x = c(1.2, 2.5), type = "numeric", valueRange = c(1, 3)) validateVector(x = c("a", "b"), type = "character", allowedValues = c("a", "b", "c")) validateVector( x = as.Date("2020-01-01"), type = "Date", valueRange = as.Date(c("2020-01-01", "2020-12-31")) ) # Range validation examples validateVectorRange(x = c(5, 10), type = "numeric", valueRange = c(1, 10)) validateVectorRange(x = c("a", "b"), type = "character", valueRange = c("a", "c")) validateVectorRange( x = as.Date(c("2020-01-01")), type = "Date", valueRange = as.Date(c("2020-01-01", "2020-12-31")) ) validateVectorRange(x = 1:3, type = "integer", valueRange = c(1L, 5L)) # Allowed values validation examples validateVectorValues(x = c("a", "b"), type = "character", allowedValues = c("a", "b", "c")) validateVectorValues(x = c(2L, 4L), type = "integer", allowedValues = c(1L, 2L, 3L, 4L)) validateVectorValues(x = c(TRUE), type = "logical", allowedValues = c(TRUE, FALSE))