Skip to content

Commit

Permalink
imported magrittr pipe and finished docs
Browse files Browse the repository at this point in the history
  • Loading branch information
Qile0317 committed May 26, 2024
1 parent 7ecf6b3 commit 52389de
Show file tree
Hide file tree
Showing 49 changed files with 521 additions and 25 deletions.
3 changes: 3 additions & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export(divide)
export(enumerate)
export(getAvgHex)
export(getChar)
export(getPlotDims)
export(getUniquePairsUpTo)
export(getfirst)
export(getlast)
Expand All @@ -33,9 +34,11 @@ export(stripSpaces)
export(substrEnd)
export(subtract)
export(tableToNumeric)
export(test_quietly_that)
export(val)
export(val1)
export(zip)
exportPattern("^[[:alpha:]]+")
importFrom(Rcpp,evalCpp)
importFrom(magrittr,"%>%")
useDynLib(FastUtils, .registration = TRUE)
1 change: 1 addition & 0 deletions R/FastUtils-package.R
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
"_PACKAGE"

## usethis namespace: start
#' @importFrom magrittr %>%
#' @importFrom Rcpp evalCpp
#' @useDynLib FastUtils, .registration = TRUE
#' @exportPattern "^[[:alpha:]]+"
Expand Down
8 changes: 8 additions & 0 deletions R/character.R
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,14 @@
#' @return A substring of the input character string.
#' @export
#' @keywords character
#'
#' @seealso [substr()]
#'
#' @examples
#' substrEnd("12345", 1, 1)
#' substrEnd("12345", 1, 2)
#' substrEnd("12345", 2, 3)
#'
substrEnd <- function(x, start, endDiff) {
substr(x, start, nchar(x) - endDiff)
}
36 changes: 24 additions & 12 deletions R/color.R
Original file line number Diff line number Diff line change
Expand Up @@ -2,33 +2,45 @@
#'
#' This function computes the average color of the provided hex color values.
#'
#' @param ... Hex color values as character strings.
#'
#' @return A single hex color value representing the average of the input colors.
#' @param ... Hex color values as character strings. Could also be any number
#' of character vectors (including lists) which will all be coerced into a single
#' characters, assuming they are valid hex codes.
#'
#' @return A single hex color character representing the average of the input colors.
#' @export
#' @keywords color
#'
#'
#' @source \url{https://stackoverflow.com/questions/649454}
#'
#' @examples
#' getAvgHex("#00000", "#FF00FF")
#' getAvgHex(c("#008040", "#00000", "#FF00FF"))
#' getAvgHex(list("#008040", "#00000"), "#FF00FF", c("#FF00FF"))
#'
getAvgHex <- function(...) {
grDevices::rgb(
round(t(Reduce(
function(x, y) (x+y)/2,
lapply(unlist(list(...)), grDevices::col2rgb)
))),
maxColorValue = 256
)

hex_vector <- unlist(list(...))

Reduce(add, lapply(hex_vector, grDevices::col2rgb)) %>%
divide(length(hex_vector)) %>%
round() %>%
t() %>%
grDevices::rgb(maxColorValue = 256)
}

#' Scale the Brightness of a Hex Color
#'
#' This function scales the brightness of a hex color by a given factor.
#' This function scales the brightness of hex colors by a given factor.
#'
#' @param hex Hex color values as characters.
#' @param scaleFactor A numeric value to scale the brightness. A value of 1 returns the original color.
#'
#' @return A hex color value with adjusted brightness.
#' @export
#' @keywords color
#' @examples
#' scaleHex("#404040", 2)
#'
scaleHex <- function(hex, scaleFactor) {

if (all(scaleFactor == 1)) return(hex)
Expand Down
29 changes: 29 additions & 0 deletions R/dataInitialization.R
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,11 @@
#' @return A vector of the specified type and size, optionally initialized with a value.
#' @export
#' @keywords dataInitialization
#' @examples
#' # Create a numeric vector of length 5
#' initV("numeric", 5)
#' # Create a logical vector of length 3 initialized with TRUE
#' initV("logical", 3, TRUE)
initV <- function(typeFunc, x, initVal = NULL) {
if (is(typeFunc, "character")) {
v <- vector(typeFunc, x)
Expand All @@ -29,6 +34,13 @@ initV <- function(typeFunc, x, initVal = NULL) {
#' @return A list of the specified size and names, optionally initialized with a value.
#' @export
#' @keywords dataInitialization
#' @examples
#' # 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)
initList <- function(x, initVal = NULL) {

if (is.character(x)) {
Expand All @@ -47,6 +59,9 @@ initList <- function(x, initVal = NULL) {
#' @return An empty table structure.
#' @export
#' @keywords dataInitialization
#' @examples
#' # Create an empty table
#' initEmptyTable()
initEmptyTable <- function() {
structure(
integer(0),
Expand All @@ -65,6 +80,10 @@ initEmptyTable <- function() {
#' @return A numeric vector with names preserved from the table.
#' @export
#' @keywords dataInitialization
#' @examples
#' # Convert a table to numeric
#' tbl <- table(c("a", "b", "a"))
#' tableToNumeric(tbl)
tableToNumeric <- function(x) {
structure(as.numeric(x), names = names(x))
}
Expand All @@ -78,6 +97,10 @@ tableToNumeric <- function(x) {
#' @return A table with the same names and values as the input vector.
#' @export
#' @keywords dataInitialization
#' @examples
#' # Convert a named numeric vector to a table
#' vec <- c(a = 1, b = 2, c = 3)
#' namedNumericToTable(vec)
namedNumericToTable <- function(x) {
output <- as.integer(x)
names(output) <- names(x)
Expand All @@ -89,13 +112,19 @@ namedNumericToTable <- function(x) {
#' Create a Hash Table
#'
#' 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.
#'
#' @param keys A vector of keys for the hash table.
#' @param init_vals Optional initial value for the hash table.
#'
#' @return A hash table with the specified keys and initial values.
#' @export
#' @keywords dataInitialization
#' @examples
#' # 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)
createHash <- function(keys, init_vals = NULL) {
if (missing(keys)) return(hash::hash())
keys <- unique(keys)
Expand Down
8 changes: 7 additions & 1 deletion R/ggplot.R
Original file line number Diff line number Diff line change
@@ -1,12 +1,18 @@
#' Get the xmin, xmax, ymin, ymax of a ggplot Object
#'
#' 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.
#'
#' @param plt A ggplot object.
#'
#' @return A list with elements `xr` (a vector of xmin and xmax) and `yr` (a vector of ymin and ymax).
#' @export
#' @keywords ggplot
#' @noRd
#' @examples
#' getPlotDims(ggplot(mtcars) + geom_point(aes(mpg, cyl)))
#'
getPlotDims <- function(plt) {
built_plt_layout <- ggplot2::ggplot_build(plt)$layout
list(
Expand Down
12 changes: 11 additions & 1 deletion R/higherOrderFunctions.R
Original file line number Diff line number Diff line change
@@ -1,12 +1,22 @@
#' Create a Mutator Function
#'
#' This function creates a mutator function based on a specified binary operator. The mutator function updates a variable in the parent frame by applying the binary operator with a given value.
#' This function 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.
#'
#' @param binaryOperator A binary operator function to apply for the mutation.
#'
#' @return A function that takes a variable and a value, applying the binary operator to update the variable in the parent frame.
#' @export
#' @keywords higherOrderFunctions
#'
#' @examples
#' "%+=%" <- createMutator(add)
#' x <- 1
#' x %+=% 1
#'
createMutator <- function(binaryOperator) {
function(var, val) {
eval(
Expand Down
18 changes: 18 additions & 0 deletions R/indexing.R
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,15 @@
#' @return The last `n` elements of the input.
#' @export
#' @keywords indexing
#' @examples
#' # 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)
getlast <- function(x, n = 1) {
UseMethod("getlast")
}
Expand All @@ -31,6 +40,15 @@ getlast.default <- function(x, n = 1) {
#' @return The first `n` elements of the input.
#' @export
#' @keywords indexing
#' @examples
#' # 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)
getfirst <- function(x, n = 1) {
UseMethod("getfirst")
}
Expand Down
18 changes: 17 additions & 1 deletion R/interactivity.R
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,20 @@
#' @return The result of the expression with messages suppressed and output captured.
#' @export
#' @keywords interactivity
quietly <- function(e) suppressMessages(capture.output(e))
#' @examples
#'
#' quietly(print(1))
#'
#' quietly({
#' print(1)
#' print(2)
#' print(3)
#' })
#'
#' a <- 1
#' quietly({
#' a <- a + 1
#' print(a)
#' })
#'
quietly <- function(e) suppressMessages(invisible(capture.output(e)))
36 changes: 35 additions & 1 deletion R/iteration.R
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@
#' @return A list of unique pairs of integers up to the specified number.
#' @export
#' @keywords iteration
#' @examples
#' # Generate unique pairs up to 3 (one-indexed)
#' getUniquePairsUpTo(3)
#' # Generate unique pairs up to 3 (zero-indexed)
#' getUniquePairsUpTo(3, oneIndexed = FALSE)
getUniquePairsUpTo <- function(x, oneIndexed = TRUE) {
if (x <= 1) return(list())
rcppGetUniquePairsUpTo(as.integer(x), oneIndexed = oneIndexed)
Expand All @@ -22,18 +27,35 @@ getUniquePairsUpTo <- function(x, oneIndexed = TRUE) {
#' @return A list of lists, where each inner list contains the elements from the corresponding positions in the input vectors or lists.
#' @export
#' @keywords iteration
#' @examples
#' # Zip two vectors
#' zip(c(1, 2, 3), c("a", "b", "c"))
#' # Zip three vectors
#' zip(c(1, 2), c("x", "y"), c(TRUE, FALSE))
zip <- function(...) mapply(list, ..., SIMPLIFY = FALSE)

#' Enumerate Elements with Indices
#'
#' This function pairs elements of vectors or lists with their indices.
#' 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.
#'
#' @param ... Vectors or lists to be enumerated.
#' @param zero_indexed A logical indicating whether indexing should start from zero. Default is FALSE.
#'
#' @return A list of lists, where each inner list contains an index and the corresponding elements from the input vectors or lists.
#' @export
#' @keywords iteration
#'
#' @seealso [ind()], [val()], [val1()]
#'
#' @examples
#' # Enumerate a vector
#' enumerate(c("a", "b", "c"))
#' # Enumerate a vector starting from zero
#' enumerate(c("a", "b", "c"), zero_indexed = TRUE)
#' # Enumerate two vectors
#' enumerate(c(1, 2), c("x", "y"))
enumerate <- function(..., zero_indexed = FALSE) {
zip(seq_along(..1) - zero_indexed, ...)
}
Expand All @@ -47,6 +69,10 @@ enumerate <- function(..., zero_indexed = FALSE) {
#' @return The index of the enumerated element.
#' @export
#' @keywords iteration
#' @examples
#' # Extract index from an enumerated element
#' elem <- list(1, "a")
#' ind(elem)
ind <- function(elem) elem[[1]]

#' Get Value from Enumerated Element by Index
Expand All @@ -59,6 +85,10 @@ ind <- function(elem) elem[[1]]
#' @return The value at the specified index in the enumerated element.
#' @export
#' @keywords iteration
#' @examples
#' # Extract value from an enumerated element by index
#' elem <- list(1, "a", "b")
#' val(elem, 2)
val <- function(elem, index) elem[[index + 1]]

#' Get First Value from Enumerated Element
Expand All @@ -70,4 +100,8 @@ val <- function(elem, index) elem[[index + 1]]
#' @return The first value in the enumerated element.
#' @export
#' @keywords iteration
#' @examples
#' # Extract the first value from an enumerated element
#' elem <- list(1, "a", "b")
#' val1(elem)
val1 <- function(elem) val(elem, 1)
Loading

0 comments on commit 52389de

Please sign in to comment.