Title: | Fast, Readable Utility Functions |
---|---|
Description: | A wide variety of tools for general data analysis, wrangling, spelling, statistics, visualizations, package development, and more. All functions have vectorized implementations whenever possible. Exported names are designed to be readable, with longer names possessing short aliases. |
Authors: | Qile Yang [cre, aut, cph] |
Maintainer: | Qile Yang <[email protected]> |
License: | MIT + file LICENSE |
Version: | 0.2.1 |
Built: | 2024-11-16 05:37:09 UTC |
Source: | https://github.com/qile0317/fastutils |
This function adds two objects. If both objects are numeric vectors,
it performs element-wise addition. If one or both objects are strings,
it concatenates them. For other objects, it attempts to use the +
method defined for the class of the objects.
add(x, y)
add(x, y)
x |
An object. |
y |
An object. |
The result of adding the two objects.
# Add two numeric vectors add(c(1, 2, 3), c(4, 5, 6)) # Concatenate two strings add("hello", "world") # Add a number and a string (concatenation) add(1, " world")
# Add two numeric vectors add(c(1, 2, 3), c(4, 5, 6)) # Concatenate two strings add("hello", "world") # Add a number and a string (concatenation) add(1, " world")
This function bounds a number within a specified range. This function is vectorized in a way such that either or both lowerbound and upperbound can be length 1 or the same length as the input vector.
bound(num, lowerbound, upperbound)
bound(num, lowerbound, upperbound)
num |
A numeric vector to be bounded. |
lowerbound |
The lower bound of the range. |
upperbound |
The upper bound of the range. |
A numeric vector with elements bounded within the specified range.
bound(1, 0, 2) bound(1:10, -1, 5)
bound(1, 0, 2) bound(1:10, -1, 5)
This function finds the closest word in a set of words to a given word based on a specified distance function.
closestWord(s, strset, distFunc = utils::adist)
closestWord(s, strset, distFunc = utils::adist)
s |
A character string. |
strset |
A set of character strings. |
distFunc |
A function to compute distance between strings.
Default is |
The closest word in the set to the given word.
# Find the closest word to "hello" in the set c("hallo", "hullo", "hey") closestWord("hello", c("hallo", "hullo", "hey"))
# Find the closest word to "hello" in the set c("hallo", "hullo", "hey") closestWord("hello", c("hallo", "hullo", "hey"))
This function converts a specified column of a data frame to row names, ensuring uniqueness if necessary.
colToRownames(df, col, .remove = TRUE, .uniqueSep = ".")
colToRownames(df, col, .remove = TRUE, .uniqueSep = ".")
df |
A data frame. |
col |
A character string specifying the name of the column to convert to row names. |
.remove |
A logical indicating whether to remove the selected column after converting to row names. Default is TRUE. |
.uniqueSep |
A character string to separate duplicate row names when
ensuring uniqueness
with |
A data frame with the specified column as row names. If .remove
is TRUE, the original column is removed.
# Convert the 'ID' column to row names df <- data.frame(ID = c("A", "B", "C"), Value = c(10, 20, 30)) colToRownames(df, "ID") # Convert the 'ID' column to row names and keep the column df <- data.frame(ID = c("A", "B", "C"), Value = c(10, 20, 30)) colToRownames(df, "ID", .remove = FALSE)
# Convert the 'ID' column to row names df <- data.frame(ID = c("A", "B", "C"), Value = c(10, 20, 30)) colToRownames(df, "ID") # Convert the 'ID' column to row names and keep the column df <- data.frame(ID = c("A", "B", "C"), Value = c(10, 20, 30)) colToRownames(df, "ID", .remove = FALSE)
This function creates a hash table from a set of keys and optional initial
value. Note that it is simply a convenience wrapper for the hash
package.
createHash(keys, initVals = NULL)
createHash(keys, initVals = NULL)
keys |
A vector of keys for the hash table. |
initVals |
Optional initial value for the hash table. |
A hash table with the specified keys and initial values.
# Create a hash table with keys and no initial values createHash(c("a", "b", "c")) # Create a hash table with keys and initial value of 0 createHash(c("a", "b", "c"), 0)
# Create a hash table with keys and no initial values createHash(c("a", "b", "c")) # Create a hash table with keys and initial value of 0 createHash(c("a", "b", "c"), 0)
Creates a mutator function based on a specified binary operator.
The output mutator function updates a variable in the parent frame by
applying the binary operator with a given value. It's recommended to use
this function to easily construct special functions in the form of %f%
where f
can be any symbol of choice. See examples.
createMutator(binaryOperator)
createMutator(binaryOperator)
binaryOperator |
A binary operator function to apply for the mutation. |
A function that takes a variable and a value, applying the binary operator to update the variable in the parent frame.
"%+=%" <- createMutator(add) x <- 1 x %+=% 1 x # becomes 2
"%+=%" <- createMutator(add) x <- 1 x %+=% 1 x # becomes 2
This function creates a package loader function that can install and load packages from CRAN, Bioconductor, or GitHub, optionally displaying verbose output. This function can be useful in new R instances with little dependencies available.
The function takes the following arguments:
cran
bioc
gh
verbose
where cranand
bioctake character vectors of package names on CRAN and Bioconductor, while
ghtakes character vectors with the formatting
githubUsername/packageName.
verbose' takes in a logical for whether
to display additional informative messages in the REPL.
The function will not install packages that can already be loaded by default.
createPkgLoader(lib = .libPaths()[1])
createPkgLoader(lib = .libPaths()[1])
lib |
A character vector specifying the library directory for package
installation of the output function. Defaults to the current default
package installation directory in |
A function that installs and loads packages.
# Create the package loader function loader <- createPkgLoader() # # commented usage example # loader( # cran = c("dplyr", "ggplot2"), # bioc = c("GenomicRanges", "Biobase"), # gh = c("tidyverse/dplyr"), # verbose = FALSE # )
# Create the package loader function loader <- createPkgLoader() # # commented usage example # loader( # cran = c("dplyr", "ggplot2"), # bioc = c("GenomicRanges", "Biobase"), # gh = c("tidyverse/dplyr"), # verbose = FALSE # )
This function divides one number by another.
divide(x, y)
divide(x, y)
x |
A numeric vector. |
y |
A numeric vector. |
A numeric vector representing the quotient of the input vectors.
# Divide two numeric vectors divide(c(10, 20, 30), c(2, 4, 5))
# Divide two numeric vectors divide(c(10, 20, 30), c(2, 4, 5))
This function encloses a string with specified characters on the left and the right.
enclose(x, left, right)
enclose(x, left, right)
x |
A character string to enclose. |
left |
A character string to prepend. |
right |
A character string to append. |
A new character string with x
enclosed by left
and right
.
enclose("text", "[", "]") # returns "[text]"
enclose("text", "[", "]") # returns "[text]"
This function encloses a string with parentheses.
encloseBr(x)
encloseBr(x)
x |
A character string to enclose. |
A new character string with x
enclosed by parentheses.
encloseBr("text") # returns "(text)"
encloseBr("text") # returns "(text)"
This function pairs elements of vectors or lists with their indices. The
output
is meant to be used in a for loop, and each element extracted with the
ind()
, val()
, or val1()
functions. A slightly lighter weight
alternative to itertools::enumerate()
enumerateit(..., zeroIndexed = FALSE)
enumerateit(..., zeroIndexed = FALSE)
... |
Vectors or lists to be enumerated. |
zeroIndexed |
A logical indicating whether indexing should start from zero. Default is FALSE. |
A list of lists, where each inner list contains an index and the corresponding elements from the input vectors or lists.
# Enumerate a vector enumerateit(c("a", "b", "c")) # Enumerate a vector starting from zero enumerateit(c("a", "b", "c"), zero_indexed = TRUE) # Enumerate two vectors enumerateit(c(1, 2), c("x", "y"))
# Enumerate a vector enumerateit(c("a", "b", "c")) # Enumerate a vector starting from zero enumerateit(c("a", "b", "c"), zero_indexed = TRUE) # Enumerate two vectors enumerateit(c(1, 2), c("x", "y"))
This function evaluates a string as R code, and stops if an error occurs. This can be useful for evaluating code that is generated dynamically.
evalText(..., envir = parent.frame())
evalText(..., envir = parent.frame())
... |
the R code to evaluate as characters. Will be joined when evaluating. |
envir |
the environment in which to evaluate the code. Defaults to the parent frame of the function. |
the result of the evaluation
# Set names of a vector x <- 1:3 x <- evalText("setNames(x, c('A', 'B', 'C'))") x
# Set names of a vector x <- 1:3 x <- evalText("setNames(x, c('A', 'B', 'C'))") x
This function scans Rd documentation files in the specified package's \man
directory to identify which functions lack certain documentation sections
like \examples
. If there are no missing sections in all the Rd files, then
the output is a character(0)
findMissingRdSections( sectionName, pkg = ".", ignore = NULL, .ignore = "-package$" ) fmrs(sectionName, pkg = ".", ignore = NULL, .ignore = "-package$")
findMissingRdSections( sectionName, pkg = ".", ignore = NULL, .ignore = "-package$" ) fmrs(sectionName, pkg = ".", ignore = NULL, .ignore = "-package$")
sectionName |
A character vector of the Rd sections to look for. |
pkg |
The path to the package directory, defaulting to the current directory. |
ignore |
Additional Regexes of function names to be ignored in the output. |
.ignore |
More regexes of functions to ignore set by default. Will be
appended with
the |
Character vector of function names that are missing any of the specified sections in their Rd files. May be length 0 if all fulfill criteria.
try( findMissingRdSections(c("examples", "example"), pkg = "."), silent = TRUE )
try( findMissingRdSections(c("examples", "example"), pkg = "."), silent = TRUE )
This function fixes the column names of a given object so that all words are spaced by a specified delimiter, and any special characters are replaced according to a substitution map.
fixColnames( object, invalidRegex = joinRegex(" ", "\\)", "\\(", "\\.", "/"), spacing = "_", subMap = NULL, .subMap = list(`%+` = "pct", `\\$+` = "dollars", `\\++` = "plus", `-+` = "minus", `\\*+` = "star", `#+` = "cnt", `&+` = "and", `@+` = "at"), unique = FALSE )
fixColnames( object, invalidRegex = joinRegex(" ", "\\)", "\\(", "\\.", "/"), spacing = "_", subMap = NULL, .subMap = list(`%+` = "pct", `\\$+` = "dollars", `\\++` = "plus", `-+` = "minus", `\\*+` = "star", `#+` = "cnt", `&+` = "and", `@+` = "at"), unique = FALSE )
object |
A data frame or matrix. |
invalidRegex |
A character string containing a regex pattern for invalid characters to replace. Default is "( )|(\()|(\))|(\.)|(/)". |
spacing |
A character string to replace invalid characters with. Default is "_". |
subMap |
A named list where the names are regular expressions and the
values are the replacement strings. These substitutions are applied before
|
.subMap |
A named list where the names are regular expressions and the
values are the replacement strings. These substitutions are applied after
|
unique |
A logical indicating whether to ensure unique column names by appending a suffix if necessary. Default is FALSE. |
The data frame or matrix with fixed column names.
# Fix column names of a data frame df <- data.frame( `A (1)` = c(1, 2, 3), `B/C` = c(4, 5, 6), `D+E` = c(7, 8, 9) ) fixColnames(df)
# Fix column names of a data frame df <- data.frame( `A (1)` = c(1, 2, 3), `B/C` = c(4, 5, 6), `D+E` = c(7, 8, 9) ) fixColnames(df)
This function computes the average color of the provided hex color values.
getAvgHex(...)
getAvgHex(...)
... |
Hex color values as character strings. Could also be any number of character vectors (including lists) which will all be coerced into one character, assuming they are valid hex codes. |
A single hex color character representing the average of the input colors.
https://stackoverflow.com/questions/649454
getAvgHex("#000000", "#FF00FF") getAvgHex(c("#008040", "#000000", "#FF00FF")) # very nonstandard but possible way to input hexes. Essentially, # any combination of vectors will work. getAvgHex(list("#008040", "#000000"), "#FF00FF", c("#FF00FF"))
getAvgHex("#000000", "#FF00FF") getAvgHex(c("#008040", "#000000", "#FF00FF")) # very nonstandard but possible way to input hexes. Essentially, # any combination of vectors will work. getAvgHex(list("#008040", "#000000"), "#FF00FF", c("#FF00FF"))
This function retrieves a character at a specific index from a string.
getChar(x, index)
getChar(x, index)
x |
A character string. |
index |
The index of the character to retrieve. If it is length 1,
then the same character is retrieved for all elements of |
The character at the specified index.
# Get the character at index 2 getChar("hello", 2)
# Get the character at index 2 getChar("hello", 2)
This function generates a failure message string from a given condition. The message includes the context of the call and the specific condition message.
getFailStr(cond)
getFailStr(cond)
cond |
A condition object representing an error or warning - probably
from a |
A character string containing the failure message.
tryCatch(stop("Example error"), error = function(e) getFailStr(e))
tryCatch(stop("Example error"), error = function(e) getFailStr(e))
This function retrieves the first n
elements of a vector or list.
getfirst(x, n = 1) ## Default S3 method: getfirst(x, n = 1)
getfirst(x, n = 1) ## Default S3 method: getfirst(x, n = 1)
x |
A vector, list, or other supported data type. |
n |
An integer specifying the number of elements to retrieve from the start. Default is 1. |
The first n
elements of the input.
# Get the first element of a vector getfirst(c(1, 2, 3, 4, 5)) # Get the first 2 elements of a vector getfirst(c(1, 2, 3, 4, 5), 2) # Get the first element of a list getfirst(list("a", "b", "c")) # Get the first 2 elements of a list getfirst(list("a", "b", "c"), 2)
# Get the first element of a vector getfirst(c(1, 2, 3, 4, 5)) # Get the first 2 elements of a vector getfirst(c(1, 2, 3, 4, 5), 2) # Get the first element of a list getfirst(list("a", "b", "c")) # Get the first 2 elements of a list getfirst(list("a", "b", "c"), 2)
This function retrieves the last n
elements of a vector or list.
getlast(x, n = 1) ## Default S3 method: getlast(x, n = 1)
getlast(x, n = 1) ## Default S3 method: getlast(x, n = 1)
x |
A vector, list, or other supported data type. |
n |
An integer specifying the number of elements to retrieve from the end. Default is 1. |
The last n
elements of the input.
# Get the last element of a vector getlast(c(1, 2, 3, 4, 5)) # Get the last 2 elements of a vector getlast(c(1, 2, 3, 4, 5), 2) # Get the last element of a list getlast(list("a", "b", "c")) # Get the last 2 elements of a list getlast(list("a", "b", "c"), 2)
# Get the last element of a vector getlast(c(1, 2, 3, 4, 5)) # Get the last 2 elements of a vector getlast(c(1, 2, 3, 4, 5), 2) # Get the last element of a list getlast(list("a", "b", "c")) # Get the last 2 elements of a list getlast(list("a", "b", "c"), 2)
This function retrieves keywords from all package documentation files located
in the /man
directory of the specified R package. It can return a unique
list of keywords or a frequency distribution of these keywords as a table
object, sorted by the keys.
Note that the "internal" keyword is ignored.
getPkgKeywords(pkg = ".", asDistribution = FALSE)
getPkgKeywords(pkg = ".", asDistribution = FALSE)
pkg |
The path to the R package directory. |
asDistribution |
Logical; if FALSE, returns a character vector of unique keywords. If TRUE, returns a table with the frequency of each keyword. |
If asDistribution
is FALSE, a sorted character vector of
unique keywords is returned. If asDistribution
is TRUE, a table of
keywords and their frequencies is returned. If no keywords were detected,
returns a character of length 0.
getPkgKeywords() getPkgKeywords(asDistribution = TRUE)
getPkgKeywords() getPkgKeywords(asDistribution = TRUE)
This function retrieves the minimum and maximum x and y dimensions of a ggplot object. Note that it is the dimension of the plot within the x and y axis and not the dimensions of the actual output image itself. This may be useful for numerical computations when modifying plots, but can be slow since it builds the actual plot first.
getPlotDims(plt)
getPlotDims(plt)
plt |
A ggplot object. |
A list with elements xr
(a vector of xmin and xmax) and yr
(a
vector of ymin and ymax).
library(ggplot2) getPlotDims(ggplot(mtcars) + geom_point(aes(mpg, cyl)))
library(ggplot2) getPlotDims(ggplot(mtcars) + geom_point(aes(mpg, cyl)))
This function generates all unique pairs of integers up to a given number.
getUniquePairsUpTo(x, oneIndexed = TRUE)
getUniquePairsUpTo(x, oneIndexed = TRUE)
x |
An integer specifying the upper limit for pairs. |
oneIndexed |
A logical indicating whether the pairs should be one indexed. Default is TRUE. |
A list of unique pairs of integers up to the specified number.
# Generate unique pairs up to 3 (one-indexed) getUniquePairsUpTo(3) # Generate unique pairs up to 3 (zero-indexed) getUniquePairsUpTo(3, oneIndexed = FALSE)
# Generate unique pairs up to 3 (one-indexed) getUniquePairsUpTo(3) # Generate unique pairs up to 3 (zero-indexed) getUniquePairsUpTo(3, oneIndexed = FALSE)
The greplDir
function searches for a specified pattern in all files within
a given directory. It allows for optional exclusion of files matching a
specified regular expression. Note that all files are assumed to be a single
string, with each line joined by the newline character "\n"
.
greplDir(fpattern, dirPath = getwd(), fIgnoreRegex = NULL, ...)
greplDir(fpattern, dirPath = getwd(), fIgnoreRegex = NULL, ...)
fpattern |
Character. The pattern to search for within the files. |
dirPath |
Character. The path to the directory containing files to be searched. |
fIgnoreRegex |
Character. A regular expression to match file names that should be ignored (default is NULL). |
... |
Additional arguments passed to |
A named logical vector indicating which files contain the pattern. The names attribute contains the file names.
result <- tryCatch( greplDir("error", fIgnoreRegex = "\\.log$"), warning = function(w) c(exFname = TRUE), error = function(e) c(exFname = TRUE) ) # its even more useful to use `base::which` on the result to # get matches and mismatches - this returns it with names # by default which(result) which(!result)
result <- tryCatch( greplDir("error", fIgnoreRegex = "\\.log$"), warning = function(w) c(exFname = TRUE), error = function(e) c(exFname = TRUE) ) # its even more useful to use `base::which` on the result to # get matches and mismatches - this returns it with names # by default which(result) which(!result)
This function extracts the index from an enumerated element.
ind(elem)
ind(elem)
elem |
An enumerated element. |
The index of the enumerated element.
# Extract index from an enumerated element elem <- list(1, "a") ind(elem)
# Extract index from an enumerated element elem <- list(1, "a") ind(elem)
This function creates an empty data frame and assigns the specified column names with zero rows.
initDataFrameWithColnames(colnames = NULL)
initDataFrameWithColnames(colnames = NULL)
colnames |
A character vector specifying the names of the columns for the data frame. This vector will be attempted to be coerced to a character. |
A data frame with the specified column names. Non unique names will
be handled by the conventions of data.frame()
.
prefixes.
# Create a data frame with specified column names initialized with NA initDataFrameWithColnames(c("Name", "Age", "Gender"))
# Create a data frame with specified column names initialized with NA initDataFrameWithColnames(c("Name", "Age", "Gender"))
This function initializes an empty table.
initEmptyTable()
initEmptyTable()
An empty table structure.
# Create an empty table initEmptyTable()
# Create an empty table initEmptyTable()
This function initializes a list based on size or names, with an optional initial value.
initList(x = NULL, initVal = NULL)
initList(x = NULL, initVal = NULL)
x |
A character vector as names, or an numeric indicating the size of the list. |
initVal |
an optional initial value for all elements of the list. |
A list of the specified size and names, optionally initialized with a value.
# Create a list with 3 elements initList(3) # Create a named list initialized with NULL initList(c("a", "b", "c")) # Create a list with 2 elements initialized with 0 initList(2, 0)
# Create a list with 3 elements initList(3) # Create a named list initialized with NULL initList(c("a", "b", "c")) # Create a list with 2 elements initialized with 0 initList(2, 0)
This function scans all files in the specified R directory based on its name,
excluding some based on the patterns provided in the ignore
argument,
and creates testthat
files if they are missing. Useful for when many source
code files were created from rapid development and unit testing has yet to be
setup.
initTestthat( rDir = "R", testDir = file.path("tests", "testthat"), .ignore = c("-package.R$", "-class.R$", "^data.R$", "^zzz.R$", "^RcppExports.R$"), ignore = NULL )
initTestthat( rDir = "R", testDir = file.path("tests", "testthat"), .ignore = c("-package.R$", "-class.R$", "^data.R$", "^zzz.R$", "^RcppExports.R$"), ignore = NULL )
rDir |
The directory containing R source files. Default is "R". |
testDir |
The directory where |
.ignore |
A character vector specifying regex patterns of files to
ignore. Defaults
to common patterns |
ignore |
A character vector of extra regex patterns of R files to ignore |
No return value, called for side effects.
try({ initTestthat() initTestthat(rDir = "src", testDir = "tests") initTestthat(ignore = c("^foo", "-bar.R$")) }, silent = TRUE)
try({ initTestthat() initTestthat(rDir = "src", testDir = "tests") initTestthat(ignore = c("^foo", "-bar.R$")) }, silent = TRUE)
This function initializes a vector based on a specified type and size, with an optional initial value.
initV(typeFunc, x, initVal = NULL)
initV(typeFunc, x, initVal = NULL)
typeFunc |
A character string indicating the type of the vector or a function to create the vector. |
x |
The length of the vector. |
initVal |
An optional initial value to fill the vector. |
A vector of the specified type and size, optionally initialized with a value.
# Create a numeric vector of length 5 initV("numeric", 5) # Create a logical vector of length 3 initialized with TRUE initV("logical", 3, TRUE)
# Create a numeric vector of length 5 initV("numeric", 5) # Create a logical vector of length 3 initialized with TRUE initV("logical", 3, TRUE)
This function checks if a number is within a specified range. This function is vectorized in a way such that either or both lowerbound and upperbound can be length 1 or the same length as the input vector.
isBound(num, lowerbound, upperbound)
isBound(num, lowerbound, upperbound)
num |
A numeric vector to be checked. |
lowerbound |
The lower bound of the range. |
upperbound |
The upper bound of the range. |
A logical vector indicating whether each element is within the specified range.
isBound(1, 0, 2) isBound(1:10, -1, 5)
isBound(1, 0, 2) isBound(1:10, -1, 5)
This function checks if a given string adheres to camelCase naming conventions, starting with a lowercase letter followed by any combination of upper and lower case letters.
isCamelCase(x)
isCamelCase(x)
x |
A character string to check. |
TRUE if the string is camelCase, FALSE otherwise.
isCamelCase("camelCase") # returns TRUE isCamelCase("CamelCase") # returns FALSE isCamelCase("camelcase") # returns TRUE
isCamelCase("camelCase") # returns TRUE isCamelCase("CamelCase") # returns FALSE isCamelCase("camelcase") # returns TRUE
This function checks if a number is even.
isEven(x)
isEven(x)
x |
A numeric vector. |
A logical vector indicating whether each element is even.
# Check if numbers are even isEven(c(1, 2, 3, 4))
# Check if numbers are even isEven(c(1, 2, 3, 4))
This function checks if a number is odd.
isOdd(x)
isOdd(x)
x |
A numeric vector. |
A logical vector indicating whether each element is odd.
# Check if numbers are odd isOdd(c(1, 2, 3, 4))
# Check if numbers are odd isOdd(c(1, 2, 3, 4))
This function checks if a given string adheres to PascalCase naming conventions, starting with an uppercase letter followed by any combination of upper and lower case letters.
isPascalCase(x)
isPascalCase(x)
x |
A character string to check. |
TRUE if the string is PascalCase, FALSE otherwise.
isPascalCase("PascalCase") # returns TRUE isPascalCase("pascalCase") # returns FALSE isPascalCase("Pascalcase") # returns TRUE
isPascalCase("PascalCase") # returns TRUE isPascalCase("pascalCase") # returns FALSE isPascalCase("Pascalcase") # returns TRUE
This function checks if a given string adheres to snake_case naming conventions. By default (strict = TRUE), it only allows lowercase letters separated by underscores. If strict is FALSE, uppercase letters are also permitted.
isSnakeCase(x, strict = TRUE)
isSnakeCase(x, strict = TRUE)
x |
A character string to check. |
strict |
Logical indicating whether the string should strictly contain only lowercase letters (TRUE) or can include uppercase ones (FALSE). Default is TRUE. |
TRUE if the string is snake_case according to the specified strictness, FALSE otherwise.
isSnakeCase("snake_case") # returns TRUE isSnakeCase("Snake_Case") # returns FALSE isSnakeCase("snake_case", FALSE) # returns TRUE isSnakeCase("Snake_Case", FALSE) # returns TRUE
isSnakeCase("snake_case") # returns TRUE isSnakeCase("Snake_Case") # returns FALSE isSnakeCase("snake_case", FALSE) # returns TRUE isSnakeCase("Snake_Case", FALSE) # returns TRUE
This function checks if a character is a vowel.
isVowel(x)
isVowel(x)
x |
A character. |
TRUE if the character is a vowel, FALSE otherwise.
# Check if 'a' is a vowel isVowel("a") # Check if 'b' is a vowel isVowel("b")
# Check if 'a' is a vowel isVowel("a") # Check if 'b' is a vowel isVowel("b")
This function simply joins a vector of regex characters by union,
and produces a single character regex in the form of (foo)|(bar)
.
joinRegex(...)
joinRegex(...)
... |
character vectors of the regex expressions to join. Both vectors and individual characters of any length will work |
a character of the unioned regex
joinRegex(c("^foo", "bar$")) joinRegex("^foo", "bar$", "[bB]az")
joinRegex(c("^foo", "bar$")) joinRegex("^foo", "bar$", "[bB]az")
This function lists only the files in a specified directory, excluding
directories. It is useful when you need to process or analyze only the files
within a directory without including subdirectories. The base::list.files()
function lists both files and directories, so this function provides a more
convenient way to obtain just the files.
listFiles(dirPath, ...)
listFiles(dirPath, ...)
dirPath |
Character. The path to the directory from which to list files. |
... |
Additional arguments passed to |
A character vector of file paths.
listFiles(getwd()) listFiles(getwd(), pattern = "\\.R$", recursive = TRUE)
listFiles(getwd()) listFiles(getwd(), pattern = "\\.R$", recursive = TRUE)
This function multiplies two numbers.
multiply(x, y)
multiply(x, y)
x |
A numeric vector. |
y |
A numeric vector. |
A numeric vector representing the product of the input vectors.
# Multiply two numeric vectors multiply(c(2, 3, 4), c(5, 6, 7))
# Multiply two numeric vectors multiply(c(2, 3, 4), c(5, 6, 7))
This function sets new row names for a data frame based on a tidy evaluation expression.
mutateToRownames(.data, expr, .remove = FALSE, .uniqueSep = ".")
mutateToRownames(.data, expr, .remove = FALSE, .uniqueSep = ".")
.data |
A data frame. |
expr |
A tidy evaluation expression specifying the columns to use for the new row names. |
.remove |
A logical indicating whether to remove the selected columns. Default is FALSE. |
.uniqueSep |
A character string to separate duplicate row names when
ensuring uniqueness
with |
A data frame with updated row names.
library(dplyr) mtcars %>% head() %>% mutateToRownames(wt + 3*vs)
library(dplyr) mtcars %>% head() %>% mutateToRownames(wt + 3*vs)
This function converts a named numeric vector to a table.
namedNumericToTable(x)
namedNumericToTable(x)
x |
A named numeric vector. |
A table with the same names and values as the input vector.
# Convert a named numeric vector to a table vec <- c(a = 1, b = 2, c = 3) namedNumericToTable(vec)
# Convert a named numeric vector to a table vec <- c(a = 1, b = 2, c = 3) namedNumericToTable(vec)
This function prepends an indefinite article ("a" or "an") to a string based on whether it starts with a vowel or not.
prependIndefArticle(x) pia(x)
prependIndefArticle(x) pia(x)
x |
A character string. |
The string with an indefinite article prepended.
# Prepend an indefinite article to "apple" prependIndefArticle("apple") # Prepend an indefinite article to "banana" prependIndefArticle("banana")
# Prepend an indefinite article to "apple" prependIndefArticle("apple") # Prepend an indefinite article to "banana" prependIndefArticle("banana")
This function suppresses messages and captures output from an expression. Note that this does NOT return the result of the expression! It is intended to be used in contexts where certain operations with side effects are performed but the verbosity should be suppressed.
quietly(e)
quietly(e)
e |
An expression to evaluate. |
The result of the expression with messages suppressed and output captured.
quietly(print(1)) quietly({ print(1) print(2) print(3) }) a <- 1 quietly({ a <- a + 1 print(a) }) print(a) #> 2
quietly(print(1)) quietly({ print(1) print(2) print(3) }) a <- 1 quietly({ a <- a + 1 print(a) }) print(a) #> 2
This function removes new snapshots created by vdiffr
tests. It is useful
when you want to remove new snapshots that were created during testing and
are no longer needed.
removeVdiffrNewSnapShots( pkg = getwd(), snapDir = file.path("tests", "testthat", "_snaps"), verbose = TRUE ) rmns( pkg = getwd(), snapDir = file.path("tests", "testthat", "_snaps"), verbose = TRUE )
removeVdiffrNewSnapShots( pkg = getwd(), snapDir = file.path("tests", "testthat", "_snaps"), verbose = TRUE ) rmns( pkg = getwd(), snapDir = file.path("tests", "testthat", "_snaps"), verbose = TRUE )
pkg |
The path to the package directory. |
snapDir |
The path to the directory containing the snapshots. Default
is |
verbose |
Logical; if TRUE, prints the paths of the new snapshots that |
NULL (invisible) - used for side effects
removeVdiffrNewSnapShots()
removeVdiffrNewSnapShots()
This function removes elements from an indexable object (e.g., a named vector or list) where the names match a specified regular expression.
rmByName(x, pattern, silent = FALSE)
rmByName(x, pattern, silent = FALSE)
x |
An indexable object (e.g., a named vector, list, or data frame). |
pattern |
A character containing a regular expression(s) to match the names of elements to be removed. |
silent |
A logical indicating whether to silence a warning if no names are detected. |
The input object with elements removed based on the name regex.
myList <- list(a = 1, b_test = 2, c = 3, d_test = 4) rmByName(myList, "_test")
myList <- list(a = 1, b_test = 2, c = 3, d_test = 4) rmByName(myList, "_test")
This function converts the row names of a data frame to a specified column. Note that if the specified column already exists, it is overwritten.
rownamesToCol(df, colname = "rownames")
rownamesToCol(df, colname = "rownames")
df |
A data frame. |
colname |
A character string specifying the name of the new column to contain the row names. Defaults to "rownames". |
A data frame with the row names converted to a column.
# Convert row names to a column named 'ID' df <- data.frame(Value = c(10, 20, 30)) rownames(df) <- c("A", "B", "C") rownamesToCol(df, "ID")
# Convert row names to a column named 'ID' df <- data.frame(Value = c(10, 20, 30)) rownames(df) <- c("A", "B", "C") rownamesToCol(df, "ID")
This function scales the brightness of hex colors by a given factor.
scaleHex(hex, scaleFactor)
scaleHex(hex, scaleFactor)
hex |
Hex color values as characters. |
scaleFactor |
A numeric value to scale the brightness. A value of 1 returns the original color. |
A hex color value with adjusted brightness.
scaleHex("#404040", 2)
scaleHex("#404040", 2)
This function sets new column names for a given data frame or matrix.
setColnames(object, newColnames)
setColnames(object, newColnames)
object |
A data frame or matrix. |
newColnames |
A character vector specifying the new column names. |
The data frame or matrix with updated column names.
# Set new column names for a data frame df <- data.frame(A = c(1, 2, 3), B = c(4, 5, 6)) setColnames(df, c("X", "Y"))
# Set new column names for a data frame df <- data.frame(A = c(1, 2, 3), B = c(4, 5, 6)) setColnames(df, c("X", "Y"))
Improvement to stats::setNames()
sets new names for an object,
ensuring that the length of the new names matches the length of the object.
Additionally, if the length of newNames is one, it is repeated to match
the length of the object.
setNames(object, newNames)
setNames(object, newNames)
object |
An object. |
newNames |
A character vector specifying the new names. |
The object with updated names.
# Set new names for a vector x <- c(1, 2, 3) x <- setNames(x, c("A", "B", "C")) # some syntactic sugar can be achieved with a special mutator `%setNames%` <- createMutator(setNames) x %setNames% c("D", "E", "F")
# Set new names for a vector x <- c(1, 2, 3) x <- setNames(x, c("A", "B", "C")) # some syntactic sugar can be achieved with a special mutator `%setNames%` <- createMutator(setNames) x %setNames% c("D", "E", "F")
This function sets new row names for a given data frame or matrix.
setRownames(object, newRownames)
setRownames(object, newRownames)
object |
A data frame or matrix. |
newRownames |
A character vector specifying the new row names. |
The data frame or matrix with updated row names.
# Set new row names for a data frame df <- data.frame(A = c(1, 2, 3), B = c(4, 5, 6)) setRownames(df, c("row1", "row2", "row3"))
# Set new row names for a data frame df <- data.frame(A = c(1, 2, 3), B = c(4, 5, 6)) setRownames(df, c("row1", "row2", "row3"))
This function splits strings formatted in camelCase or PascalCase into their component words. It can handle words where uppercase letters transition to lowercase letters, and it is capable of handling strings with sequences of uppercase letters followed by lowercase letters, effectively separating acronyms from camelCase beginnings.
splitCamel(x, conseq = TRUE) splitPascal(x, conseq = TRUE)
splitCamel(x, conseq = TRUE) splitPascal(x, conseq = TRUE)
x |
A character vector containing CamelCase or PascalCase strings to be split. |
conseq |
Logical indicating whether consecutive uppercase letters should be treated as part of the previous word (TRUE) or as separate words (FALSE). Default is TRUE. |
A list of character vectors, each containing the parts of the
corresponding CamelCase or PascalCase string split at the appropriate
transitions. If conseq
is FALSE, acronyms followed by words are
separated.
<stackoverflow.com/questions/8406974/splitting-camelcase-in-r>
splitCamel("splitCamelCaseIntoWords") splitCamel(c("fooBar", "FOOBar", "anotherFOOBarTest"), conseq = FALSE)
splitCamel("splitCamelCaseIntoWords") splitCamel(c("fooBar", "FOOBar", "anotherFOOBarTest"), conseq = FALSE)
This function splits a string formatted in snake_case into its component words, using underscores as delimiters. It is useful for parsing identifiers or variable names that follow snake_case naming conventions.
splitSnake(x)
splitSnake(x)
x |
A character string in snake_case to be split. |
A list of character vectors, each containing the parts of the string split at underscores.
splitSnake("this_is_snake_case") splitSnake("another_example_here")
splitSnake("this_is_snake_case") splitSnake("another_example_here")
This function checks if a string starts with a vowel.
startsWithVowel(x)
startsWithVowel(x)
x |
A character string. |
TRUE if the string starts with a vowel, FALSE otherwise.
# Check if "apple" starts with a vowel startsWithVowel("apple") # Check if "banana" starts with a vowel startsWithVowel("banana")
# Check if "apple" starts with a vowel startsWithVowel("apple") # Check if "banana" starts with a vowel startsWithVowel("banana")
This function provides a wrapper around the base stop()
function,
but it automatically sets call.
to FALSE, which means the function
call itself is not included in the resulting error message. This makes error
messages cleaner.
The domain
argument can be used to specify a translation domain.
stopp(..., domain = NULL)
stopp(..., domain = NULL)
... |
Arguments passed on to |
domain |
The translation domain, NULL by default. |
No return value, this function stops execution of the program.
try(stopp("This is a custom stop message without the call."), silent = TRUE)
try(stopp("This is a custom stop message without the call."), silent = TRUE)
This function removes spaces from a character string.
stripSpaces(x)
stripSpaces(x)
x |
A character string. |
The string with spaces removed.
# Remove spaces from "hello world" stripSpaces("hello world")
# Remove spaces from "hello world" stripSpaces("hello world")
Extract a substring from a given start position to the position
determined by subtracting endDiff
from the string length.
substrEnd(x, start, endDiff)
substrEnd(x, start, endDiff)
x |
A character string from which the substring is extracted. |
start |
The starting position for the substring extraction. |
endDiff |
The difference to subtract from the string length to determine the end position. |
A substring of the input character string.
substrEnd("12345", 1, 1) substrEnd("12345", 1, 2) substrEnd("12345", 2, 3)
substrEnd("12345", 1, 1) substrEnd("12345", 1, 2) substrEnd("12345", 2, 3)
This function subtracts one number from another.
subtract(x, y)
subtract(x, y)
x |
A numeric vector. |
y |
A numeric vector. |
A numeric vector representing the difference between the input vectors.
# Subtract two numeric vectors subtract(c(10, 20, 30), c(1, 2, 3))
# Subtract two numeric vectors subtract(c(10, 20, 30), c(1, 2, 3))
This function converts a table to a numeric vector.
tableToNumeric(x)
tableToNumeric(x)
x |
A table to be converted. |
A numeric vector with names preserved from the table.
# Convert a table to numeric tbl <- table(c("a", "b", "a")) tableToNumeric(tbl)
# Convert a table to numeric tbl <- table(c("a", "b", "a")) tableToNumeric(tbl)
This function runs a test_that
block quietly, suppressing messages and
output from any verbose functions.
test_quietly_that(desc, code)
test_quietly_that(desc, code)
desc |
A description of the test. |
code |
The code to be tested. |
No return value, called for side effects.
# Run a test quietly test_quietly_that("quiet test example", { testthat::expect_equal(1 + 1, 2) })
# Run a test quietly test_quietly_that("quiet test example", { testthat::expect_equal(1 + 1, 2) })
This function attempts to split characters into its component words (and by default, all in lowercase) based on camelCase, PascalCase, or snake_case conventions. If the string doesn't match any of these conventions, it returns all groups of letters.
trySplitWords(..., conseq = TRUE, strictSnake = FALSE, uncase = TRUE)
trySplitWords(..., conseq = TRUE, strictSnake = FALSE, uncase = TRUE)
... |
character(s) to be split, treated as a single vector after unlisting. |
conseq |
A logical indicating whether the |
strictSnake |
A logical indicating the |
uncase |
A logical indicating whether to remove all casing in the output to lowercase. |
A list of character vectors, each containing the parts of the string split into individual words.
splitCamel
, splitPascal
,
splitSnake
, isCamelCase
,
isPascalCase
, isSnakeCase
trySplitWords("camelCaseExample") trySplitWords("PascalCaseExample") trySplitWords( "snake_case_example", c("more_snake_cases"), "third_snake_case" ) trySplitWords("some|random|case") trySplitWords("Space Words", "UPPER_CASE", uncase = TRUE)
trySplitWords("camelCaseExample") trySplitWords("PascalCaseExample") trySplitWords( "snake_case_example", c("more_snake_cases"), "third_snake_case" ) trySplitWords("some|random|case") trySplitWords("Space Words", "UPPER_CASE", uncase = TRUE)
This function extracts the value from an enumerated element by the given index.
val(elem, index)
val(elem, index)
elem |
An enumerated element. |
index |
The index of the value to extract. |
The value at the specified index in the enumerated element.
# Extract value from an enumerated element by index elem <- list(1, "a", "b") val(elem, 2)
# Extract value from an enumerated element by index elem <- list(1, "a", "b") val(elem, 2)
This function extracts the first value from an enumerated element.
val1(elem)
val1(elem)
elem |
An enumerated element. |
The first value in the enumerated element.
# Extract the first value from an enumerated element elem <- list(1, "a", "b") val1(elem)
# Extract the first value from an enumerated element elem <- list(1, "a", "b") val1(elem)
This function validates an object using a list of checks. If any check
fails, an error handler is called and a default value is returned. This
function is intended to slightly simplify cases where a long list of
complex and convoluted predetermined checks are needed. For simpler cases
like type checking, it is recommended to use stopifnot()
or
assertthat::assert_that()
.
validateObject(obj, checks, errorHandler = warningp, defaultReturn = NULL)
validateObject(obj, checks, errorHandler = warningp, defaultReturn = NULL)
obj |
The object to validate. |
checks |
A single function or list of functions, each taking the object as an argument and returning NULL if the check passes or an error message if the check fails. |
errorHandler |
A function to handle errors, taking the error message as
an argument. Default is |
defaultReturn |
The value to return if any check fails. Default is NULL. |
The original object if all checks pass, or defaultReturn
if any
check fails.
# Define some checks checkNotNull <- function(x) if (is.null(x)) "Object is NULL" else NULL checkIsNumeric <- function(x) { if (!is.numeric(x)) "Object is not numeric" else NULL } # Validate an object obj <- 42 validateObject(obj, list(checkNotNull, checkIsNumeric)) # Validate an object that fails a check obj <- NULL try( validateObject( obj, list(checkNotNull, checkIsNumeric, errorHandler = stop) ), silent = TRUE )
# Define some checks checkNotNull <- function(x) if (is.null(x)) "Object is NULL" else NULL checkIsNumeric <- function(x) { if (!is.numeric(x)) "Object is not numeric" else NULL } # Validate an object obj <- 42 validateObject(obj, list(checkNotNull, checkIsNumeric)) # Validate an object that fails a check obj <- NULL try( validateObject( obj, list(checkNotNull, checkIsNumeric, errorHandler = stop) ), silent = TRUE )
This function provides a wrapper around the base warning
function, adding flexibility to warnings by setting call.
to FALSE
automatically. This modification means that the function call is not included
in the warning message, streamlining the output for users.
warningp(...)
warningp(...)
... |
Arguments passed on to |
No return value, this function issues a warning.
try(warningp( "This is a custom warning message without the call." ), silent = TRUE)
try(warningp( "This is a custom warning message without the call." ), silent = TRUE)
This function combines multiple vectors or lists element-wise into
a list of lists. It's a slightly lighter weight alternative to
itertools::izip()
zipit(...)
zipit(...)
... |
Vectors or lists to be combined. |
A list of lists, where each inner list contains the elements from the corresponding positions in the input vectors or lists.
# Zip two vectors zipit(c(1, 2, 3), c("a", "b", "c")) # Zip three vectors zipit(c(1, 2), c("x", "y"), c(TRUE, FALSE))
# Zip two vectors zipit(c(1, 2, 3), c("a", "b", "c")) # Zip three vectors zipit(c(1, 2), c("x", "y"), c(TRUE, FALSE))