| Title: | Package Utility Functions |
|---|---|
| Description: | A collection of package utility functions written in 'base' R. |
| Authors: | Brett Klamer [aut, cre] |
| Maintainer: | Brett Klamer <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.0.1 |
| Built: | 2026-10-21 00:51:14 UTC |
| Source: | https://bitbucket.org/bklamer/bkbase |
Infix equality operator that resolves missing values instead of propagating them.
x %==% yx %==% y
x |
(atomic vector) |
y |
(atomic vector) |
base::== returns NA whenever either operand is NA.
%==% resolves those positions and never returns NA.
For each pair of compared elements the result is
TRUE when both x and y are NA.
FALSE when exactly one of x and y is NA.
The value of x == y when neither is NA.
NaN is treated the same as NA, because is.na(NaN) is TRUE.
NaN %==% NaN is TRUE and NaN %==% NA is TRUE.
x and y are recycled to a common length following standard R rules.
A logical vector of length max(length(x), length(y)).
The result never contains NA.
#---------------------------------------------------------------------------- # %==% examples #---------------------------------------------------------------------------- library(bkbase) # both NA gives TRUE, exactly one NA gives FALSE 1:3 %==% c(1:2, NA) # TRUE TRUE FALSE NA %==% NA # TRUE # NaN is treated the same as NA 1:3 %==% c(1:2, NaN) # TRUE TRUE FALSE NaN %==% NaN # TRUE NaN %==% NA # TRUE # base `==` propagates NA instead 1:3 == c(1:2, NA) # TRUE TRUE NA 1:3 == c(1:2, NaN) # TRUE TRUE NA#---------------------------------------------------------------------------- # %==% examples #---------------------------------------------------------------------------- library(bkbase) # both NA gives TRUE, exactly one NA gives FALSE 1:3 %==% c(1:2, NA) # TRUE TRUE FALSE NA %==% NA # TRUE # NaN is treated the same as NA 1:3 %==% c(1:2, NaN) # TRUE TRUE FALSE NaN %==% NaN # TRUE NaN %==% NA # TRUE # base `==` propagates NA instead 1:3 == c(1:2, NA) # TRUE TRUE NA 1:3 == c(1:2, NaN) # TRUE TRUE NA
Infix operator for matching that forces NA in x to propagate in results.
x %in2% tablex %in2% table
x |
(atomic vector) |
table |
(atomic vector) |
base::%in% treats NA in x as an ordinary value.
NA %in% c(1, 2, 3) is FALSE and NA %in% c(NA) is TRUE.
You may not want this behavior because membership of a missing value is itself unknown.
%in2% instead returns NA for every position where x is NA, regardless of whether table contains NA.
For all non-missing elements of x, the result equals base::%in%.
NaN is treated the same as NA and also propagates to NA.
A logical vector with length length(x).
base::%in%,
base::match(),
%==%
#---------------------------------------------------------------------------- # %in2% examples #---------------------------------------------------------------------------- library(bkbase) # base::`%in%` behavior NA %in% c(1, 2, 3) # FALSE NA %in% c(NA) # TRUE # bkbase::`%in2%` (always propagate NA from x) NA %in2% c(1, 2, 3) # NA NA %in2% c(NA) # NA # Mixed vectors c(NA, 1) %in% c(1, 2, 3) # FALSE TRUE c(NA, 1) %in2% c(1, 2, 3) # NA TRUE c(NA, 1) %in% c(NA, 2, 3) # TRUE FALSE c(NA, 1) %in2% c(NA, 2, 3) # NA FALSE#---------------------------------------------------------------------------- # %in2% examples #---------------------------------------------------------------------------- library(bkbase) # base::`%in%` behavior NA %in% c(1, 2, 3) # FALSE NA %in% c(NA) # TRUE # bkbase::`%in2%` (always propagate NA from x) NA %in2% c(1, 2, 3) # NA NA %in2% c(NA) # NA # Mixed vectors c(NA, 1) %in% c(1, 2, 3) # FALSE TRUE c(NA, 1) %in2% c(1, 2, 3) # NA TRUE c(NA, 1) %in% c(NA, 2, 3) # TRUE FALSE c(NA, 1) %in2% c(NA, 2, 3) # NA FALSE
Returns TRUE if all values in a logical vector are TRUE.
A stricter, surprise-free version of base::all().
all2(x, na.rm = FALSE)all2(x, na.rm = FALSE)
x |
( |
na.rm |
( |
Suppose you have a numeric vector y and want to validate all values are greater than zero using base::all(y > 0).
If y contains NAs and all nonmissing elements are greater than 0, the result will be NA.
You then might use base::all(y > 0, na.rm = TRUE), however, this assumes NAs are ok to exclude.
In this scenario, all2(y > 0) would return FALSE instead of NA.
all(NULL) and all(logical(0)) both return TRUE.
all2() returns FALSE for both cases.
all(NA, na.rm = TRUE) returns TRUE.
all2(NA, na.rm = TRUE) returns FALSE.
logical(1).
#---------------------------------------------------------------------------- # all2() examples #---------------------------------------------------------------------------- library(bkbase) x <- c(1, 2, 3, NA) all2(x > 0) all(x > 0) all2(x > 0, na.rm = TRUE) all(x > 0, na.rm = TRUE) all2(NULL) all(NULL) all2(logical(0)) all(logical(0)) all2(numeric(0)) all(numeric(0)) all2(NA, na.rm = TRUE) all(NA, na.rm = TRUE) all2(NA, na.rm = FALSE) all(NA, na.rm = FALSE)#---------------------------------------------------------------------------- # all2() examples #---------------------------------------------------------------------------- library(bkbase) x <- c(1, 2, 3, NA) all2(x > 0) all(x > 0) all2(x > 0, na.rm = TRUE) all(x > 0, na.rm = TRUE) all2(NULL) all(NULL) all2(logical(0)) all(logical(0)) all2(numeric(0)) all(numeric(0)) all2(NA, na.rm = TRUE) all(NA, na.rm = TRUE) all2(NA, na.rm = FALSE) all(NA, na.rm = FALSE)
Compute a position-wise logical AND across multiple logical inputs, allowing up to a specified fraction of missing values before returning NA.
and(..., .na_allowed = 0.2)and(..., .na_allowed = 0.2)
... |
( |
.na_allowed |
( |
This is a tolerance-aware variant of logical conjunction over multiple inputs (e.g., x & y & z).
Each output position corresponds to one vector index, or to one row when a matrix or data.frame is supplied.
The result is FALSE when any input at that position is FALSE.
Otherwise, the result is NA when the fraction of missing values exceeds .na_allowed.
If the missing fraction is within tolerance, missing values are treated as TRUE and the result is TRUE.
For each position (row) across inputs, let be the number of NAs and be the number of FALSEs.
Define the missing fraction .
Then:
Notes:
When .na_allowed = 0, behavior matches strict AND: NAs propagate only when no input is FALSE.
When , missingness never forces NA.
NAs are treated as TRUE, so the result is FALSE iff any FALSE is present, otherwise TRUE.
A logical vector with values TRUE, FALSE, or NA per the rule in Details.
The length equals the length of each input vector, or the number of rows of a matrix or data.frame.
#---------------------------------------------------------------------------- # and() examples #---------------------------------------------------------------------------- library(bkbase) x <- c(TRUE, TRUE, TRUE, FALSE, TRUE) y <- c(TRUE, TRUE, NA, TRUE, NA) z <- c(TRUE, NA, TRUE, TRUE, NA) # Base R strict AND x & y & z # NA tolerance at 20% and(x, y, z, .na_allowed = 0.2) # NA tolerance at 40% and(x, y, z, .na_allowed = 0.4) # Single data.frame input df <- data.frame(x = x, y = y, z = z) and(df, .na_allowed = 0.4) # FALSE dominates even when NA is present and(FALSE, NA, .na_allowed = 0)#---------------------------------------------------------------------------- # and() examples #---------------------------------------------------------------------------- library(bkbase) x <- c(TRUE, TRUE, TRUE, FALSE, TRUE) y <- c(TRUE, TRUE, NA, TRUE, NA) z <- c(TRUE, NA, TRUE, TRUE, NA) # Base R strict AND x & y & z # NA tolerance at 20% and(x, y, z, .na_allowed = 0.2) # NA tolerance at 40% and(x, y, z, .na_allowed = 0.4) # Single data.frame input df <- data.frame(x = x, y = y, z = z) and(df, .na_allowed = 0.4) # FALSE dominates even when NA is present and(FALSE, NA, .na_allowed = 0)
Returns TRUE if any nonmissing values in a logical vector are TRUE.
any2(x)any2(x)
x |
( |
Missing values are excluded before evaluation.
Compared with base::any(), any2() has stricter behavior:
any2() never returns NA.
any2() returns FALSE for non-logical input.
any2() returns FALSE for logical(0) and NULL.
logical(1).
#---------------------------------------------------------------------------- # any2() examples #---------------------------------------------------------------------------- library(bkbase) x <- c(1, 2, 3, NA) any2(x < 0) any(x < 0, na.rm = TRUE) any(x < 0, na.rm = FALSE) any2(NA) any(NA) any2(1L) any(1L) any2(c(TRUE, NA)) any2(c(FALSE, NA)) any2(c(NA, NA)) any2(logical(0)) any(logical(0)) any2(NULL) any(NULL)#---------------------------------------------------------------------------- # any2() examples #---------------------------------------------------------------------------- library(bkbase) x <- c(1, 2, 3, NA) any2(x < 0) any(x < 0, na.rm = TRUE) any(x < 0, na.rm = FALSE) any2(NA) any(NA) any2(1L) any(1L) any2(c(TRUE, NA)) any2(c(FALSE, NA)) any2(c(NA, NA)) any2(logical(0)) any(logical(0)) any2(NULL) any(NULL)
Coerces input to missing values (NA) of the same type.
as_na(x)as_na(x)
x |
(object) |
Object of same class as x.
Each column of a data.frame keeps its type.
NULL returns NULL.
#---------------------------------------------------------------------------- # as_na() examples #---------------------------------------------------------------------------- library(bkbase) as_na(data.frame(a = 1:3)) as_na(matrix(1:3)) as_na(list(a = 1:3)) as_na(1:3) as_na(letters[1:3]) as_na(factor(letters[1:3])) as_na(as.Date("2020-01-01"))#---------------------------------------------------------------------------- # as_na() examples #---------------------------------------------------------------------------- library(bkbase) as_na(data.frame(a = 1:3)) as_na(matrix(1:3)) as_na(list(a = 1:3)) as_na(1:3) as_na(letters[1:3]) as_na(factor(letters[1:3])) as_na(as.Date("2020-01-01"))
Join the elements of an atomic vector into one readable string, such as "'a', 'b', and 'c'".
Use csw() to list values in messages, warnings, and errors.
csw( x, n = Inf, quote = !(is.numeric(x) || is.logical(x) || is.complex(x)), conjunction = "and", tail = "count", period = FALSE, width = Inf )csw( x, n = Inf, quote = !(is.numeric(x) || is.logical(x) || is.complex(x)), conjunction = "and", tail = "count", period = FALSE, width = Inf )
x |
(atomic vector or |
n |
( |
quote |
( |
conjunction |
( |
tail |
( |
period |
( |
width |
( |
The function converts x to character with as.character().
Round or format numbers before you call csw() if you need a fixed number of digits.
Numbers formatted as character, for example by format() or round2(), get quotes unless you set quote = FALSE.
When conjunction is a string, the function puts it before the last element.
Two elements get no comma, as in "'a' and 'b'".
Three or more elements get a comma before the conjunction, as in "'a', 'b', and 'c'".
When x has more than n elements, the function shows the first n elements and then adds the text that tail selects.
Because the "count" tail is the last element of the list, it gets the conjunction and the period, as in "'a', 'b', and 24 more.".
The "ellipsis" tail turns off conjunction and period.
By default, the function does not wrap lines.
When the output is part of a longer message, wrap the full message instead, for example with fstr_wrap().
When width is finite, the function puts line breaks only between elements.
It does not split an element or change the characters in it.
An element that is wider than width gets a line of its own.
The period counts toward width.
Because NA elements get no quotes, a missing value is different from the string "NA".
The values NaN, Inf, and -Inf are not missing, and quote applies to them as to other values.
NULL and zero-length x return character(0).
character(1), or character(0) when x has length zero.
Line breaks are "\n".
#---------------------------------------------------------------------------- # csw() example #---------------------------------------------------------------------------- library(bkbase) # Strings get quotes, and "and" goes before the last element. csw(c("mpg", "cyl", "disp")) # Numbers get no quotes. Show the first 3 values and count the remainder. csw(c(2, 3, 5, 7, 11, 13), n = 3) # Put the list in a message, then wrap the full message. msg <- paste0( "Argument `x` must be one of ", csw(month.name, conjunction = "or"), "." ) message(fstr_wrap(msg, width = 60))#---------------------------------------------------------------------------- # csw() example #---------------------------------------------------------------------------- library(bkbase) # Strings get quotes, and "and" goes before the last element. csw(c("mpg", "cyl", "disp")) # Numbers get no quotes. Show the first 3 values and count the remainder. csw(c(2, 3, 5, 7, 11, 13), n = 3) # Put the list in a message, then wrap the full message. msg <- paste0( "Argument `x` must be one of ", csw(month.name, conjunction = "or"), "." ) message(fstr_wrap(msg, width = 60))
Capture the expressions supplied in ... without evaluating them.
Use dots() when the expressions should remain as language objects.
Use dots_char() when the expressions should be returned as text.
dots(..., .names = TRUE, .duplicate_names = "warn") dots_char(..., .names = TRUE, .duplicate_names = "warn")dots(..., .names = TRUE, .duplicate_names = "warn") dots_char(..., .names = TRUE, .duplicate_names = "warn")
... |
(expressions) |
.names |
( |
.duplicate_names |
( |
An object with one element for each expression in ....
dots() returns a list of unevaluated expressions.
dots_char() returns a character vector of deparsed expressions.
If .names = TRUE, missing names are filled with the deparsed expression.
If .names = FALSE, missing names are left missing.
Empty ... returns list() from dots() and character(0) from dots_char().
#---------------------------------------------------------------------------- # dots() examples #---------------------------------------------------------------------------- library(bkbase) a <- 1:5 dots(a, 6:10, x = 3) dots_char(a, 6:10, x = 3) dots(a, 6:10, x = 3, .names = FALSE)#---------------------------------------------------------------------------- # dots() examples #---------------------------------------------------------------------------- library(bkbase) a <- 1:5 dots(a, 6:10, x = 3) dots_char(a, 6:10, x = 3) dots(a, 6:10, x = 3, .names = FALSE)
A convenience function between base::deparse() and base::deparse1().
fdeparse(expr, width.cutoff = 500L, ...)fdeparse(expr, width.cutoff = 500L, ...)
expr |
(expression) |
width.cutoff |
( |
... |
Further arguments passed to |
character().
#---------------------------------------------------------------------------- # fdeparse() example #---------------------------------------------------------------------------- library(bkbase) fdeparse(y ~ x)#---------------------------------------------------------------------------- # fdeparse() example #---------------------------------------------------------------------------- library(bkbase) fdeparse(y ~ x)
Create a formula object from known-good string input.
A fast, unsafe alternative to stats::formula().
fformula(x, env = parent.frame())fformula(x, env = parent.frame())
x |
( |
env |
(environment; default |
A formula object whose environment is set to env.
#---------------------------------------------------------------------------- # fformula() example #---------------------------------------------------------------------------- library(bkbase) fformula("y ~ x")#---------------------------------------------------------------------------- # fformula() example #---------------------------------------------------------------------------- library(bkbase) fformula("y ~ x")
Calculates the arithmetic mean after excluding missing values.
A fast, unsafe alternative to base::mean(x, na.rm = TRUE) for numeric vectors.
fmean(x)fmean(x)
x |
( |
numeric(1).
#---------------------------------------------------------------------------- # fmean() example #---------------------------------------------------------------------------- library(bkbase) fmean(1:3) fmean(c(1:3, NA)) fmean(NA) fmean(numeric(0))#---------------------------------------------------------------------------- # fmean() example #---------------------------------------------------------------------------- library(bkbase) fmean(1:3) fmean(c(1:3, NA)) fmean(NA) fmean(numeric(0))
Calculates the median after excluding missing values.
A fast, unsafe alternative to stats::median(x, na.rm = TRUE).
fmedian(x, is_sorted = FALSE)fmedian(x, is_sorted = FALSE)
x |
( |
is_sorted |
( |
numeric(1).
#---------------------------------------------------------------------------- # fmedian() example #---------------------------------------------------------------------------- library(bkbase) fmedian(1:3) fmedian(c(1:3, NA)) fmedian(NA) fmedian(numeric(0))#---------------------------------------------------------------------------- # fmedian() example #---------------------------------------------------------------------------- library(bkbase) fmedian(1:3) fmedian(c(1:3, NA)) fmedian(NA) fmedian(numeric(0))
Get the number of columns in a data frame.
A fast, unsafe alternative to base::ncol().
fncol(x)fncol(x)
x |
(data.frame) |
integer(1).
#---------------------------------------------------------------------------- # fncol() examples #---------------------------------------------------------------------------- library(bkbase) x <- data.frame(a = 1) fncol(x)#---------------------------------------------------------------------------- # fncol() examples #---------------------------------------------------------------------------- library(bkbase) x <- data.frame(a = 1) fncol(x)
Get the number of rows in a data frame.
A fast, unsafe alternative to base::nrow().
fnrow(x)fnrow(x)
x |
(data.frame) |
integer(1).
#---------------------------------------------------------------------------- # fnrow() examples #---------------------------------------------------------------------------- library(bkbase) x <- data.frame(a = 1) fnrow(x)#---------------------------------------------------------------------------- # fnrow() examples #---------------------------------------------------------------------------- library(bkbase) x <- data.frame(a = 1) fnrow(x)
Write an R object as a short phrase for an error, a warning, or a message.
Use format_value() to state the value that an argument received, as in "Argument `n` is 2.5, but must be a whole number.".
format_value(x)format_value(x)
x |
(any R object) |
The function writes a plain atomic vector of length 5 or less as R code, for example 3L, "bogus", NA, or c(1, 5).
A plain vector has no class and no dimensions.
The function writes a longer plain vector by its length, as in "a vector of length 10".
It writes any other object by the first element of its class, as in an object of class "factor".
A matrix, a factor, a Date, a list, and a function are not plain vectors.
The R code keeps the type and the names of x.
An integer gets the suffix L, and a typed missing value keeps its type, as in NA_real_.
Other attributes appear in a call to structure().
deparse() writes 15 significant digits by default.
With 15 digits, 2 + 4e-16 gives "2", and a message that rejects a value that is not whole then shows a whole number.
When a double element of x needs more than 15 digits, the function writes all elements with 17 significant digits, as in 2.0000000000000004.
Other doubles keep the short form, such as 0.3.
NULL gives "NULL".
Zero-length input gives R code such as "character(0)".
NA, NaN, Inf, and -Inf give the R code for the value.
character(1).
match.arg2(), csw(), base::deparse1()
#---------------------------------------------------------------------------- # format_value() example #---------------------------------------------------------------------------- library(bkbase) # State the received value in an error message. n <- 2.5 msg <- paste0( "Argument `n` is ", format_value(n), ", but must be a whole number." ) message(msg) # Short vectors give R code. Long vectors and other objects give a phrase. format_value(c(1, 5)) format_value(1:10) format_value(factor("a")) # A double that 15 digits do not give exactly gets 17 digits. format_value(2 + 4e-16)#---------------------------------------------------------------------------- # format_value() example #---------------------------------------------------------------------------- library(bkbase) # State the received value in an error message. n <- 2.5 msg <- paste0( "Argument `n` is ", format_value(n), ", but must be a whole number." ) message(msg) # Short vectors give R code. Long vectors and other objects give a phrase. format_value(c(1, 5)) format_value(1:10) format_value(factor("a")) # A double that 15 digits do not give exactly gets 17 digits. format_value(2 + 4e-16)
Calculates the standard deviation after excluding missing values.
A fast, unsafe alternative to stats::sd(x, na.rm = TRUE).
fsd(x)fsd(x)
x |
( |
numeric(1).
#---------------------------------------------------------------------------- # fsd() example #---------------------------------------------------------------------------- library(bkbase) fsd(1:3) fsd(c(1:3, NA))#---------------------------------------------------------------------------- # fsd() example #---------------------------------------------------------------------------- library(bkbase) fsd(1:3) fsd(c(1:3, NA))
Wrap each element of a character vector to a target width. CRLF/CR are normalized to LF when present and existing newlines may be preserved. Internal runs of whitespace are collapsed to single spaces between words.
fstr_wrap(x, width = 72L, indent = 0L, exdent = 0L, keep_newlines = FALSE) fstrwrap(x, width = 72L, indent = 0L, exdent = 0L, keep_newlines = FALSE)fstr_wrap(x, width = 72L, indent = 0L, exdent = 0L, keep_newlines = FALSE) fstrwrap(x, width = 72L, indent = 0L, exdent = 0L, keep_newlines = FALSE)
x |
( |
width |
( |
indent |
( |
exdent |
( |
keep_newlines |
( |
Words are defined by splitting on the regular expression \\s+, and empty tokens are dropped.
NA elements are returned as NA_character_.
When keep_newlines = TRUE, input is split into lines at "\n", each line is word-wrapped independently, and empty lines are preserved as empty strings.
A greedy algorithm buffers contiguous words and flushes them to the output when adding the next word would exceed the target width.
If the entire line fits within the width when accounting for indent, the line is returned unwrapped.
Long words are not broken; they are placed on a line even if they exceed the width.
Line length is computed as the sum of the prefix and buffered words plus inter-word spaces.
Names on the input vector are preserved on the output.
The result for each element is a single string with any inserted wraps represented by "\n".
Character vector of the same length as x.
#---------------------------------------------------------------------------- # fstr_wrap() #---------------------------------------------------------------------------- library(bkbase) # Basic wrapping txt <- "This is a simple example sentence that will be wrapped." cat(fstr_wrap(txt, width = 20)) # Indent for the first line and exdent for continuation lines txt <- "Indented wrapping across multiple lines of text." cat(fstr_wrap(txt, width = 20, indent = 2, exdent = 4)) # Existing newlines are preserved and each line is wrapped independently txt <- "First line that is somewhat long.\nSecond line that is also long." cat(fstr_wrap(txt, width = 25, exdent = 2)) txt <- "This is a sentence. Next is the second sentence. Finally, the third sentence." cat(fstr_wrap(txt, keep_newlines = FALSE)) cat(fstr_wrap(txt, keep_newlines = TRUE)) # Names preserved and NA propagated txt <- c(a = "short line", b = NA_character_) fstr_wrap(txt, width = 25)#---------------------------------------------------------------------------- # fstr_wrap() #---------------------------------------------------------------------------- library(bkbase) # Basic wrapping txt <- "This is a simple example sentence that will be wrapped." cat(fstr_wrap(txt, width = 20)) # Indent for the first line and exdent for continuation lines txt <- "Indented wrapping across multiple lines of text." cat(fstr_wrap(txt, width = 20, indent = 2, exdent = 4)) # Existing newlines are preserved and each line is wrapped independently txt <- "First line that is somewhat long.\nSecond line that is also long." cat(fstr_wrap(txt, width = 25, exdent = 2)) txt <- "This is a sentence. Next is the second sentence. Finally, the third sentence." cat(fstr_wrap(txt, keep_newlines = FALSE)) cat(fstr_wrap(txt, keep_newlines = TRUE)) # Names preserved and NA propagated txt <- c(a = "short line", b = NA_character_) fstr_wrap(txt, width = 25)
Calculates the number of times each unique element occurs after excluding missing values.
A fast, generalized alternative to base::tabulate().
ftabulate(x, is_sorted = FALSE)ftabulate(x, is_sorted = FALSE)
x |
(atomic vector) |
is_sorted |
( |
base::tabulate() only counts positive integers.
ftabulate() will count any nonmissing element type.
integer().
base::tabulate(),
base::table()
#---------------------------------------------------------------------------- # ftabulate() example #---------------------------------------------------------------------------- library(bkbase) x <- sample(1:10, size = 100, replace = TRUE) ftabulate(x) tabulate(x) table(x)#---------------------------------------------------------------------------- # ftabulate() example #---------------------------------------------------------------------------- library(bkbase) x <- sample(1:10, size = 100, replace = TRUE) ftabulate(x) tabulate(x) table(x)
Calculates the variance after excluding missing values.
A fast, unsafe alternative to stats::var(x, na.rm = TRUE).
fvar(x)fvar(x)
x |
( |
numeric(1).
#---------------------------------------------------------------------------- # fvar() example #---------------------------------------------------------------------------- library(bkbase) fvar(1:3) fvar(c(1:3, NA))#---------------------------------------------------------------------------- # fvar() example #---------------------------------------------------------------------------- library(bkbase) fvar(1:3) fvar(c(1:3, NA))
Expressions enclosed by delimiters will be evaluated or extracted and inserted into the string.
glue2( ..., .env = parent.frame(), .open = "{", .close = "}", .sep = " ", .eval = TRUE )glue2( ..., .env = parent.frame(), .open = "{", .close = "}", .sep = " ", .eval = TRUE )
... |
( |
.env |
(environment, list, or data.frame; default |
.open, .close
|
( |
.sep |
( |
.eval |
( |
An expression can span more than one line.
The function converts each value with base::as.character().
If a value has length zero, the result is character(0), as in glue::glue().
Otherwise, the function recycles the values to the length of the longest value.
The function stops with an error when the length of a value does not divide the length of the longest value.
character().
Its length is the length of the longest value, or 1 if the template has no expressions.
It is character(0) if a value has length zero.
This function was inspired by code by Posit (MIT license) and Mike Cheng (MIT license)
https://github.com/tidyverse/glue/blob/main/R/glue.R
https://github.com/coolbutuseless/gluestick/blob/main/R/gluestick.R
#---------------------------------------------------------------------------- # glue2() examples #---------------------------------------------------------------------------- library(bkbase) # Extract value from data object data <- list(name = "Fred") glue2("Hello {name}", .env = data) # Extract value from parent.frame() name <- "Fred" glue2("Hello {name}") # A vector is returned if expressions contain vectors glue2("Number {1:2}") # Evaluate expression year_current <- as.numeric(format(Sys.Date(),'%Y')) year_past <- 1970 glue2( "Today is {Sys.Date()}", "and it has been {year_current - year_past} years since 1970.", .eval = TRUE )#---------------------------------------------------------------------------- # glue2() examples #---------------------------------------------------------------------------- library(bkbase) # Extract value from data object data <- list(name = "Fred") glue2("Hello {name}", .env = data) # Extract value from parent.frame() name <- "Fred" glue2("Hello {name}") # A vector is returned if expressions contain vectors glue2("Number {1:2}") # Evaluate expression year_current <- as.numeric(format(Sys.Date(),'%Y')) year_past <- 1970 glue2( "Today is {Sys.Date()}", "and it has been {year_current - year_past} years since 1970.", .eval = TRUE )
Returns TRUE when x is an atomic vector of type integer, double, character, logical, complex, or raw and has no dim attribute.
is_atomic(x)is_atomic(x)
x |
(any object) |
This is a stricter alternative to base::is.atomic().
Only integer, double, character, logical, complex, and raw vectors return TRUE.
A dim attribute makes the result FALSE.
Matrices and arrays therefore return FALSE even when their underlying type is allowed.
The test uses base::typeof(), so classed objects built on an allowed type return TRUE.
This includes Date, POSIXct, and factor objects.
Objects stored as lists return FALSE, including data.frame and POSIXlt.
NULL returns FALSE.
Zero-length vectors of an allowed type return TRUE.
logical(1).
#---------------------------------------------------------------------------- # is_atomic() examples #---------------------------------------------------------------------------- library(bkbase) is_atomic(1) is_atomic(FALSE) is_atomic(c("a", "b")) is_atomic(integer(0)) is_atomic(raw(1)) # FALSE because of a dim attribute is_atomic(matrix(1)) # FALSE because the object is stored as a list is_atomic(data.frame(1))#---------------------------------------------------------------------------- # is_atomic() examples #---------------------------------------------------------------------------- library(bkbase) is_atomic(1) is_atomic(FALSE) is_atomic(c("a", "b")) is_atomic(integer(0)) is_atomic(raw(1)) # FALSE because of a dim attribute is_atomic(matrix(1)) # FALSE because the object is stored as a list is_atomic(data.frame(1))
Returns TRUE if x is a one-dimensional atomic vector where every element is equal to the first element.
Zero-length and length-one vectors are constant.
is_const(x)is_const(x)
x |
(atomic vector) |
NA and NaN are treated as values rather than unknown comparison results.
This means c(NA, NA) and c(NaN, NaN) are constant, while c(NA, NaN) and c(1, NA) are not constant.
Non-atomic objects and objects with dimensions return FALSE.
logical(1).
#---------------------------------------------------------------------------- # is_const() examples #---------------------------------------------------------------------------- library(bkbase) is_const(c(1, 1, 1)) is_const(c(1, 2, 1)) is_const(c(NA, NA)) is_const(c(NaN, NaN)) is_const(c(NA, NaN)) is_const(integer(0)) is_const(NULL) is_const(matrix(1, nrow = 1)) is_const(list(1, 1))#---------------------------------------------------------------------------- # is_const() examples #---------------------------------------------------------------------------- library(bkbase) is_const(c(1, 1, 1)) is_const(c(1, 2, 1)) is_const(c(NA, NA)) is_const(c(NaN, NaN)) is_const(c(NA, NaN)) is_const(integer(0)) is_const(NULL) is_const(matrix(1, nrow = 1)) is_const(list(1, 1))
Returns TRUE if x is a date (class Date).
is_date(x)is_date(x)
x |
(any object) |
logical(1).
#---------------------------------------------------------------------------- # is_date() examples #---------------------------------------------------------------------------- library(bkbase) d <- as.Date("2019-01-01") dt <- as.POSIXct("2019-01-01") is_date(d) is_date(dt)#---------------------------------------------------------------------------- # is_date() examples #---------------------------------------------------------------------------- library(bkbase) d <- as.Date("2019-01-01") dt <- as.POSIXct("2019-01-01") is_date(d) is_date(dt)
Returns TRUE if x is a date (class Date) or datetime (class POSIXct).
is_date_or_datetime(x)is_date_or_datetime(x)
x |
(any object) |
logical(1).
#---------------------------------------------------------------------------- # is_date_or_datetime() examples #---------------------------------------------------------------------------- library(bkbase) d <- as.Date("2019-01-01") dt <- as.POSIXct("2019-01-01") is_date_or_datetime(d) is_date_or_datetime(dt)#---------------------------------------------------------------------------- # is_date_or_datetime() examples #---------------------------------------------------------------------------- library(bkbase) d <- as.Date("2019-01-01") dt <- as.POSIXct("2019-01-01") is_date_or_datetime(d) is_date_or_datetime(dt)
Returns TRUE if x is a datetime (class POSIXct).
is_datetime(x)is_datetime(x)
x |
(any object) |
logical(1).
#---------------------------------------------------------------------------- # is_datetime() examples #---------------------------------------------------------------------------- library(bkbase) dt <- as.POSIXct("2019-01-01") d <- as.Date("2019-01-01") is_datetime(dt) is_datetime(d)#---------------------------------------------------------------------------- # is_datetime() examples #---------------------------------------------------------------------------- library(bkbase) dt <- as.POSIXct("2019-01-01") d <- as.Date("2019-01-01") is_datetime(dt) is_datetime(d)
Returns TRUE if x inherits from class "factor".
is_factor(x)is_factor(x)
x |
(any object) |
logical(1).
#---------------------------------------------------------------------------- # is_factor() examples #---------------------------------------------------------------------------- library(bkbase) is_factor(factor(c("a", "b"))) is_factor(factor("a", ordered = TRUE)) is_factor(factor()) is_factor("a") is_factor(NULL)#---------------------------------------------------------------------------- # is_factor() examples #---------------------------------------------------------------------------- library(bkbase) is_factor(factor(c("a", "b"))) is_factor(factor("a", ordered = TRUE)) is_factor(factor()) is_factor("a") is_factor(NULL)
Returns TRUE if x inherits from class "formula".
is_formula(x)is_formula(x)
x |
(any object) |
logical(1).
#---------------------------------------------------------------------------- # is_formula() examples #---------------------------------------------------------------------------- library(bkbase) is_formula(1:4) is_formula("y ~ x") is_formula(y ~ x)#---------------------------------------------------------------------------- # is_formula() examples #---------------------------------------------------------------------------- library(bkbase) is_formula(1:4) is_formula("y ~ x") is_formula(y ~ x)
Returns TRUE if all values in x are monotonically decreasing.
Returns FALSE for non-numeric input, NULL, and zero-length vectors.
is_monotonic_decreasing(x, na.rm = FALSE)is_monotonic_decreasing(x, na.rm = FALSE)
x |
( |
na.rm |
( |
logical(1).
#---------------------------------------------------------------------------- # is_monotonic_decreasing() examples #---------------------------------------------------------------------------- library(bkbase) is_monotonic_decreasing(10:-10) is_monotonic_decreasing(c(3.5, 2, 2, 1, 1, 0)) is_monotonic_decreasing(1) is_monotonic_decreasing(1:3) is_monotonic_decreasing(c(3:1, NA)) is_monotonic_decreasing(c(3:1, NA), na.rm = TRUE) is_monotonic_decreasing(NA_real_) is_monotonic_decreasing(NA_real_, na.rm = TRUE) is_monotonic_decreasing(numeric(0L)) is_monotonic_decreasing(NULL)#---------------------------------------------------------------------------- # is_monotonic_decreasing() examples #---------------------------------------------------------------------------- library(bkbase) is_monotonic_decreasing(10:-10) is_monotonic_decreasing(c(3.5, 2, 2, 1, 1, 0)) is_monotonic_decreasing(1) is_monotonic_decreasing(1:3) is_monotonic_decreasing(c(3:1, NA)) is_monotonic_decreasing(c(3:1, NA), na.rm = TRUE) is_monotonic_decreasing(NA_real_) is_monotonic_decreasing(NA_real_, na.rm = TRUE) is_monotonic_decreasing(numeric(0L)) is_monotonic_decreasing(NULL)
Returns TRUE if all values in x are monotonically increasing.
Returns FALSE for non-numeric input, NULL, and zero-length vectors.
is_monotonic_increasing(x, na.rm = FALSE)is_monotonic_increasing(x, na.rm = FALSE)
x |
( |
na.rm |
( |
logical(1).
#---------------------------------------------------------------------------- # is_monotonic_increasing() examples #---------------------------------------------------------------------------- library(bkbase) is_monotonic_increasing(-10:10) is_monotonic_increasing(c(0, 1, 1, 2, 2, 3.5)) is_monotonic_increasing(1) is_monotonic_increasing(3:1) is_monotonic_increasing(c(1:3, NA)) is_monotonic_increasing(c(1:3, NA), na.rm = TRUE) is_monotonic_increasing(NA_real_) is_monotonic_increasing(NA_real_, na.rm = TRUE) is_monotonic_increasing(numeric(0L)) is_monotonic_increasing(NULL)#---------------------------------------------------------------------------- # is_monotonic_increasing() examples #---------------------------------------------------------------------------- library(bkbase) is_monotonic_increasing(-10:10) is_monotonic_increasing(c(0, 1, 1, 2, 2, 3.5)) is_monotonic_increasing(1) is_monotonic_increasing(3:1) is_monotonic_increasing(c(1:3, NA)) is_monotonic_increasing(c(1:3, NA), na.rm = TRUE) is_monotonic_increasing(NA_real_) is_monotonic_increasing(NA_real_, na.rm = TRUE) is_monotonic_increasing(numeric(0L)) is_monotonic_increasing(NULL)
Returns TRUE if all values in x are probabilities.
A probability is a nonmissing numeric value bounded by [0, 1].
is_probability(x)is_probability(x)
x |
(any object) |
logical(1).
#---------------------------------------------------------------------------- # is_probability() examples #---------------------------------------------------------------------------- library(bkbase) # TRUE is_probability(c(0, 0.5, 1)) is_probability(1L) # FALSE is_probability(1.1) is_probability(NA_real_) is_probability(numeric(0L)) is_probability(NULL)#---------------------------------------------------------------------------- # is_probability() examples #---------------------------------------------------------------------------- library(bkbase) # TRUE is_probability(c(0, 0.5, 1)) is_probability(1L) # FALSE is_probability(1.1) is_probability(NA_real_) is_probability(numeric(0L)) is_probability(NULL)
Returns TRUE if x is a scalar character (character vector of length 1).
is_scalar_character(x)is_scalar_character(x)
x |
(any object) |
logical(1).
#---------------------------------------------------------------------------- # is_scalar_character() examples #---------------------------------------------------------------------------- library(bkbase) # TRUE is_scalar_character("a") is_scalar_character(NA_character_) # FALSE is_scalar_character(c("a", "b")) is_scalar_character(character(0L)) is_scalar_character(1L) is_scalar_character(NULL)#---------------------------------------------------------------------------- # is_scalar_character() examples #---------------------------------------------------------------------------- library(bkbase) # TRUE is_scalar_character("a") is_scalar_character(NA_character_) # FALSE is_scalar_character(c("a", "b")) is_scalar_character(character(0L)) is_scalar_character(1L) is_scalar_character(NULL)
Returns TRUE if x is a scalar date (class Date of length 1).
is_scalar_date(x)is_scalar_date(x)
x |
(any object) |
logical(1).
#---------------------------------------------------------------------------- # is_scalar_date() examples #---------------------------------------------------------------------------- library(bkbase) is_scalar_date(as.Date("2024-01-01")) is_scalar_date(as.POSIXct("2024-01-01")) is_scalar_date(as.Date(c("2024-01-01", "2024-01-02"))) is_scalar_date(as.POSIXct(c("2024-01-01", "2024-01-02")))#---------------------------------------------------------------------------- # is_scalar_date() examples #---------------------------------------------------------------------------- library(bkbase) is_scalar_date(as.Date("2024-01-01")) is_scalar_date(as.POSIXct("2024-01-01")) is_scalar_date(as.Date(c("2024-01-01", "2024-01-02"))) is_scalar_date(as.POSIXct(c("2024-01-01", "2024-01-02")))
Returns TRUE if x is a scalar date or datetime (class Date or POSIXct of length 1).
is_scalar_date_or_datetime(x)is_scalar_date_or_datetime(x)
x |
(any object) |
logical(1).
#---------------------------------------------------------------------------- # is_scalar_date_or_datetime() examples #---------------------------------------------------------------------------- library(bkbase) is_scalar_date_or_datetime(as.Date("2024-01-01")) is_scalar_date_or_datetime(as.POSIXct("2024-01-01")) is_scalar_date_or_datetime(as.Date(c("2024-01-01", "2024-01-02"))) is_scalar_date_or_datetime(as.POSIXct(c("2024-01-01", "2024-01-02")))#---------------------------------------------------------------------------- # is_scalar_date_or_datetime() examples #---------------------------------------------------------------------------- library(bkbase) is_scalar_date_or_datetime(as.Date("2024-01-01")) is_scalar_date_or_datetime(as.POSIXct("2024-01-01")) is_scalar_date_or_datetime(as.Date(c("2024-01-01", "2024-01-02"))) is_scalar_date_or_datetime(as.POSIXct(c("2024-01-01", "2024-01-02")))
Returns TRUE if x is a scalar datetime (class POSIXct of length 1).
is_scalar_datetime(x)is_scalar_datetime(x)
x |
(any object) |
logical(1).
#---------------------------------------------------------------------------- # is_scalar_datetime() examples #---------------------------------------------------------------------------- library(bkbase) is_scalar_datetime(as.Date("2024-01-01")) is_scalar_datetime(as.POSIXct("2024-01-01")) is_scalar_datetime(as.Date(c("2024-01-01", "2024-01-02"))) is_scalar_datetime(as.POSIXct(c("2024-01-01", "2024-01-02")))#---------------------------------------------------------------------------- # is_scalar_datetime() examples #---------------------------------------------------------------------------- library(bkbase) is_scalar_datetime(as.Date("2024-01-01")) is_scalar_datetime(as.POSIXct("2024-01-01")) is_scalar_datetime(as.Date(c("2024-01-01", "2024-01-02"))) is_scalar_datetime(as.POSIXct(c("2024-01-01", "2024-01-02")))
Returns TRUE if x is a scalar double (double-precision vector of length 1).
is_scalar_double(x)is_scalar_double(x)
x |
(any object) |
logical(1).
#---------------------------------------------------------------------------- # is_scalar_double() examples #---------------------------------------------------------------------------- library(bkbase) # TRUE is_scalar_double(0) is_scalar_double(1.5) is_scalar_double(NA_real_) # FALSE is_scalar_double(1L) is_scalar_double(c(1, 2)) is_scalar_double(numeric(0L)) is_scalar_double(NULL)#---------------------------------------------------------------------------- # is_scalar_double() examples #---------------------------------------------------------------------------- library(bkbase) # TRUE is_scalar_double(0) is_scalar_double(1.5) is_scalar_double(NA_real_) # FALSE is_scalar_double(1L) is_scalar_double(c(1, 2)) is_scalar_double(numeric(0L)) is_scalar_double(NULL)
Returns TRUE if x is a scalar factor (factor vector of length 1).
is_scalar_factor(x)is_scalar_factor(x)
x |
(any object) |
logical(1).
#---------------------------------------------------------------------------- # is_scalar_factor() examples #---------------------------------------------------------------------------- library(bkbase) # TRUE is_scalar_factor(factor("a")) is_scalar_factor(factor("a", ordered = TRUE)) is_scalar_factor(factor(NA)) # FALSE is_scalar_factor(factor(c("a", "b"))) is_scalar_factor(factor()) is_scalar_factor("a") is_scalar_factor(NULL)#---------------------------------------------------------------------------- # is_scalar_factor() examples #---------------------------------------------------------------------------- library(bkbase) # TRUE is_scalar_factor(factor("a")) is_scalar_factor(factor("a", ordered = TRUE)) is_scalar_factor(factor(NA)) # FALSE is_scalar_factor(factor(c("a", "b"))) is_scalar_factor(factor()) is_scalar_factor("a") is_scalar_factor(NULL)
Returns TRUE if x is a scalar integer (integer vector of length 1).
is_scalar_integer(x)is_scalar_integer(x)
x |
(any object) |
logical(1).
#---------------------------------------------------------------------------- # is_scalar_integer() examples #---------------------------------------------------------------------------- library(bkbase) # TRUE is_scalar_integer(1L) is_scalar_integer(NA_integer_) # FALSE is_scalar_integer(1) is_scalar_integer(1:2) is_scalar_integer(integer(0L)) is_scalar_integer(NULL)#---------------------------------------------------------------------------- # is_scalar_integer() examples #---------------------------------------------------------------------------- library(bkbase) # TRUE is_scalar_integer(1L) is_scalar_integer(NA_integer_) # FALSE is_scalar_integer(1) is_scalar_integer(1:2) is_scalar_integer(integer(0L)) is_scalar_integer(NULL)
Returns TRUE if x is a scalar logical (logical vector of length 1).
is_scalar_logical(x)is_scalar_logical(x)
x |
(any object) |
logical(1).
#---------------------------------------------------------------------------- # is_scalar_logical() examples #---------------------------------------------------------------------------- library(bkbase) # TRUE is_scalar_logical(TRUE) is_scalar_logical(FALSE) is_scalar_logical(NA) # FALSE is_scalar_logical(c(TRUE, FALSE)) is_scalar_logical(logical(0L)) is_scalar_logical(1L) is_scalar_logical(NULL)#---------------------------------------------------------------------------- # is_scalar_logical() examples #---------------------------------------------------------------------------- library(bkbase) # TRUE is_scalar_logical(TRUE) is_scalar_logical(FALSE) is_scalar_logical(NA) # FALSE is_scalar_logical(c(TRUE, FALSE)) is_scalar_logical(logical(0L)) is_scalar_logical(1L) is_scalar_logical(NULL)
Returns TRUE if x is a scalar numeric (numeric vector of length 1).
is_scalar_numeric(x)is_scalar_numeric(x)
x |
(any object) |
logical(1).
#---------------------------------------------------------------------------- # is_scalar_numeric() examples #---------------------------------------------------------------------------- library(bkbase) # TRUE is_scalar_numeric(1) is_scalar_numeric(1L) is_scalar_numeric(1.5) is_scalar_numeric(NA_real_) is_scalar_numeric(NA_integer_) # FALSE is_scalar_numeric(1:2) is_scalar_numeric(numeric(0L)) is_scalar_numeric(NA) is_scalar_numeric(as.Date("2024-10-01")) is_scalar_numeric(factor("a")) is_scalar_numeric(NULL)#---------------------------------------------------------------------------- # is_scalar_numeric() examples #---------------------------------------------------------------------------- library(bkbase) # TRUE is_scalar_numeric(1) is_scalar_numeric(1L) is_scalar_numeric(1.5) is_scalar_numeric(NA_real_) is_scalar_numeric(NA_integer_) # FALSE is_scalar_numeric(1:2) is_scalar_numeric(numeric(0L)) is_scalar_numeric(NA) is_scalar_numeric(as.Date("2024-10-01")) is_scalar_numeric(factor("a")) is_scalar_numeric(NULL)
Returns TRUE if x is a scalar probability.
A scalar probability is a length 1 nonmissing numeric value bounded by [0, 1].
is_scalar_probability(x)is_scalar_probability(x)
x |
(any object) |
logical(1).
#---------------------------------------------------------------------------- # is_scalar_probability() examples #---------------------------------------------------------------------------- library(bkbase) # TRUE is_scalar_probability(0) is_scalar_probability(0.5) is_scalar_probability(1) # FALSE is_scalar_probability(1.1) is_scalar_probability(NA_real_) is_scalar_probability(numeric(0L)) is_scalar_probability(NULL)#---------------------------------------------------------------------------- # is_scalar_probability() examples #---------------------------------------------------------------------------- library(bkbase) # TRUE is_scalar_probability(0) is_scalar_probability(0.5) is_scalar_probability(1) # FALSE is_scalar_probability(1.1) is_scalar_probability(NA_real_) is_scalar_probability(numeric(0L)) is_scalar_probability(NULL)
Returns TRUE if x is a single whole number to some tolerance.
See is_scalar_whole_numeric() to test for a scalar whole number without a tolerance.
See base::is.integer() to test for integer storage type.
is_scalar_whole_number(x, tol = 1e-08)is_scalar_whole_number(x, tol = 1e-08)
x |
(any object) |
tol |
( |
NA, NaN, Inf, and -Inf return FALSE.
Zero-length input and NULL return FALSE.
Inputs with length other than 1 return FALSE.
logical(1).
is_whole_number(),
is_scalar_whole_numeric(),
base::is.integer()
#---------------------------------------------------------------------------- # is_scalar_whole_number() examples #---------------------------------------------------------------------------- library(bkbase) # TRUE is_scalar_whole_number(1L) is_scalar_whole_number(1) is_scalar_whole_number(9.0) is_scalar_whole_number(sqrt(2)^2) is_scalar_whole_number(1 + 2^-30) is_scalar_whole_number(1e100) is_scalar_whole_number(1.00000001) # FALSE is_scalar_whole_number(1.0000001) is_scalar_whole_number(Inf) is_scalar_whole_number(c(1, 2, 3)) # Missing values and zero-length is_scalar_whole_number(NA_integer_) # FALSE is_scalar_whole_number(NA_real_) # FALSE is_scalar_whole_number(NaN) # FALSE is_scalar_whole_number(numeric(0)) # FALSE is_scalar_whole_number(NULL) # FALSE#---------------------------------------------------------------------------- # is_scalar_whole_number() examples #---------------------------------------------------------------------------- library(bkbase) # TRUE is_scalar_whole_number(1L) is_scalar_whole_number(1) is_scalar_whole_number(9.0) is_scalar_whole_number(sqrt(2)^2) is_scalar_whole_number(1 + 2^-30) is_scalar_whole_number(1e100) is_scalar_whole_number(1.00000001) # FALSE is_scalar_whole_number(1.0000001) is_scalar_whole_number(Inf) is_scalar_whole_number(c(1, 2, 3)) # Missing values and zero-length is_scalar_whole_number(NA_integer_) # FALSE is_scalar_whole_number(NA_real_) # FALSE is_scalar_whole_number(NaN) # FALSE is_scalar_whole_number(numeric(0)) # FALSE is_scalar_whole_number(NULL) # FALSE
Returns TRUE if x is a single integer, or a single double whose value is exactly equal to its truncated form.
See is_scalar_whole_number() to test for a scalar whole number within a chosen tolerance.
See base::is.integer() to test for integer storage type.
is_scalar_whole_numeric(x)is_scalar_whole_numeric(x)
x |
(any object) |
Inf and -Inf in double storage return TRUE because Inf == trunc(Inf).
NA and NaN return FALSE.
Zero-length input and NULL return FALSE.
Inputs with length other than 1 return FALSE.
logical(1).
is_whole_numeric(),
is_scalar_whole_number(),
base::is.integer()
#---------------------------------------------------------------------------- # is_scalar_whole_numeric() examples #---------------------------------------------------------------------------- library(bkbase) # TRUE is_scalar_whole_numeric(1L) is_scalar_whole_numeric(1) is_scalar_whole_numeric(9.0) is_scalar_whole_numeric(1e100) is_scalar_whole_numeric(Inf) # FALSE is_scalar_whole_numeric(1.00000001) is_scalar_whole_numeric(sqrt(2)^2) is_scalar_whole_numeric(1 + 2^-30) is_scalar_whole_numeric(c(1, 2, 3)) # Missing values and zero-length is_scalar_whole_numeric(NA_integer_) # FALSE is_scalar_whole_numeric(NA_real_) # FALSE is_scalar_whole_numeric(NaN) # FALSE is_scalar_whole_numeric(numeric(0)) # FALSE is_scalar_whole_numeric(NULL) # FALSE#---------------------------------------------------------------------------- # is_scalar_whole_numeric() examples #---------------------------------------------------------------------------- library(bkbase) # TRUE is_scalar_whole_numeric(1L) is_scalar_whole_numeric(1) is_scalar_whole_numeric(9.0) is_scalar_whole_numeric(1e100) is_scalar_whole_numeric(Inf) # FALSE is_scalar_whole_numeric(1.00000001) is_scalar_whole_numeric(sqrt(2)^2) is_scalar_whole_numeric(1 + 2^-30) is_scalar_whole_numeric(c(1, 2, 3)) # Missing values and zero-length is_scalar_whole_numeric(NA_integer_) # FALSE is_scalar_whole_numeric(NA_real_) # FALSE is_scalar_whole_numeric(NaN) # FALSE is_scalar_whole_numeric(numeric(0)) # FALSE is_scalar_whole_numeric(NULL) # FALSE
Returns TRUE if all values in x are strictly decreasing.
Returns FALSE for non-numeric input, NULL, and zero-length vectors.
is_strict_decreasing(x, na.rm = FALSE)is_strict_decreasing(x, na.rm = FALSE)
x |
( |
na.rm |
( |
logical(1).
#---------------------------------------------------------------------------- # is_strict_decreasing() examples #---------------------------------------------------------------------------- library(bkbase) is_strict_decreasing(10:-10) is_strict_decreasing(c(3.5, 2, 2, 1, 1, 0)) is_strict_decreasing(1) is_strict_decreasing(1:3) is_strict_decreasing(c(3:1, NA)) is_strict_decreasing(c(3:1, NA), na.rm = TRUE) is_strict_decreasing(NA_real_) is_strict_decreasing(NA_real_, na.rm = TRUE) is_strict_decreasing(numeric(0L)) is_strict_decreasing(NULL)#---------------------------------------------------------------------------- # is_strict_decreasing() examples #---------------------------------------------------------------------------- library(bkbase) is_strict_decreasing(10:-10) is_strict_decreasing(c(3.5, 2, 2, 1, 1, 0)) is_strict_decreasing(1) is_strict_decreasing(1:3) is_strict_decreasing(c(3:1, NA)) is_strict_decreasing(c(3:1, NA), na.rm = TRUE) is_strict_decreasing(NA_real_) is_strict_decreasing(NA_real_, na.rm = TRUE) is_strict_decreasing(numeric(0L)) is_strict_decreasing(NULL)
Returns TRUE if all values in x are strictly increasing.
Returns FALSE for non-numeric input, NULL, and zero-length vectors.
is_strict_increasing(x, na.rm = FALSE)is_strict_increasing(x, na.rm = FALSE)
x |
( |
na.rm |
( |
logical(1).
#---------------------------------------------------------------------------- # is_strict_increasing() examples #---------------------------------------------------------------------------- library(bkbase) is_strict_increasing(-10:10) is_strict_increasing(c(0, 1, 1, 2, 2, 3.5)) is_strict_increasing(1) is_strict_increasing(3:1) is_strict_increasing(c(1:3, NA)) is_strict_increasing(c(1:3, NA), na.rm = TRUE) is_strict_increasing(NA_real_) is_strict_increasing(NA_real_, na.rm = TRUE) is_strict_increasing(numeric(0L)) is_strict_increasing(NULL)#---------------------------------------------------------------------------- # is_strict_increasing() examples #---------------------------------------------------------------------------- library(bkbase) is_strict_increasing(-10:10) is_strict_increasing(c(0, 1, 1, 2, 2, 3.5)) is_strict_increasing(1) is_strict_increasing(3:1) is_strict_increasing(c(1:3, NA)) is_strict_increasing(c(1:3, NA), na.rm = TRUE) is_strict_increasing(NA_real_) is_strict_increasing(NA_real_, na.rm = TRUE) is_strict_increasing(numeric(0L)) is_strict_increasing(NULL)
Returns TRUE if x is a string (character vector of length 1).
is_string(x)is_string(x)
x |
(any object) |
logical(1).
#---------------------------------------------------------------------------- # is_string() examples #---------------------------------------------------------------------------- library(bkbase) # TRUE is_string("a") is_string(NA_character_) # FALSE is_string(c("a", "b")) is_string(character(0L)) is_string(1L) is_string(NULL)#---------------------------------------------------------------------------- # is_string() examples #---------------------------------------------------------------------------- library(bkbase) # TRUE is_string("a") is_string(NA_character_) # FALSE is_string(c("a", "b")) is_string(character(0L)) is_string(1L) is_string(NULL)
Returns TRUE if x consists of whole numbers to some tolerance.
See is_whole_numeric() to test for whole numbers without a tolerance.
See base::is.integer() to test for integer storage type.
is_whole_number(x, tol = 1e-08)is_whole_number(x, tol = 1e-08)
x |
(any object) |
tol |
( |
NA, NaN, Inf, and -Inf return FALSE.
Zero-length input and NULL return FALSE.
logical(1).
is_whole_numeric(),
is_scalar_whole_number(),
base::is.integer()
#---------------------------------------------------------------------------- # is_whole_number() examples #---------------------------------------------------------------------------- library(bkbase) # TRUE is_whole_number(1L) is_whole_number(1) is_whole_number(9.0) is_whole_number(sqrt(2)^2) is_whole_number(1 + 2^-30) is_whole_number(1e100) is_whole_number(1.00000001) # FALSE is_whole_number(1.0000001) is_whole_number(Inf) # Missing values and zero-length is_whole_number(NA_integer_) # FALSE is_whole_number(NA_real_) # FALSE is_whole_number(NaN) # FALSE is_whole_number(numeric(0)) # FALSE is_whole_number(NULL) # FALSE#---------------------------------------------------------------------------- # is_whole_number() examples #---------------------------------------------------------------------------- library(bkbase) # TRUE is_whole_number(1L) is_whole_number(1) is_whole_number(9.0) is_whole_number(sqrt(2)^2) is_whole_number(1 + 2^-30) is_whole_number(1e100) is_whole_number(1.00000001) # FALSE is_whole_number(1.0000001) is_whole_number(Inf) # Missing values and zero-length is_whole_number(NA_integer_) # FALSE is_whole_number(NA_real_) # FALSE is_whole_number(NaN) # FALSE is_whole_number(numeric(0)) # FALSE is_whole_number(NULL) # FALSE
Returns TRUE if x is an integer vector, or a double vector whose values are exactly equal to their truncated form.
See is_whole_number() to test for whole numbers within a chosen tolerance.
See base::is.integer() to test for integer storage type.
is_whole_numeric(x)is_whole_numeric(x)
x |
(any object) |
Inf and -Inf in double storage return TRUE because Inf == trunc(Inf).
NA and NaN return FALSE.
Zero-length input and NULL return FALSE.
logical(1).
is_whole_number(),
is_scalar_whole_numeric(),
base::is.integer()
#---------------------------------------------------------------------------- # is_whole_numeric() examples #---------------------------------------------------------------------------- library(bkbase) # TRUE is_whole_numeric(1L) is_whole_numeric(1) is_whole_numeric(9.0) is_whole_numeric(1e100) is_whole_numeric(Inf) # FALSE is_whole_numeric(1.00000001) is_whole_numeric(sqrt(2)^2) is_whole_numeric(1 + 2^-30) # Missing values and zero-length is_whole_numeric(NA_integer_) # FALSE is_whole_numeric(NA_real_) # FALSE is_whole_numeric(NaN) # FALSE is_whole_numeric(numeric(0)) # FALSE is_whole_numeric(NULL) # FALSE#---------------------------------------------------------------------------- # is_whole_numeric() examples #---------------------------------------------------------------------------- library(bkbase) # TRUE is_whole_numeric(1L) is_whole_numeric(1) is_whole_numeric(9.0) is_whole_numeric(1e100) is_whole_numeric(Inf) # FALSE is_whole_numeric(1.00000001) is_whole_numeric(sqrt(2)^2) is_whole_numeric(1 + 2^-30) # Missing values and zero-length is_whole_numeric(NA_integer_) # FALSE is_whole_numeric(NA_real_) # FALSE is_whole_numeric(NaN) # FALSE is_whole_numeric(numeric(0)) # FALSE is_whole_numeric(NULL) # FALSE
Recursively remove NULL and zero-length elements from a list.
list_clean(x)list_clean(x)
x |
(list) |
If inherits(x, "list") is FALSE (for example, a data.frame, an atomic vector, NULL, or any S3 object whose class vector does not contain "list"), x is returned unchanged.
Otherwise, a list is returned with NULL, zero-length, and recursively-empty elements removed at every level of nesting.
#---------------------------------------------------------------------------- # list_clean() examples #---------------------------------------------------------------------------- library(bkbase) # Removes NULL and zero-length elements, preserves names x <- list(a = 1, b = NULL, c = logical(0L), d = 2) list_clean(x) # Recursive cleaning, including fully-empty sublists y <- list(a = list(1, NULL), b = list(NULL, logical(0L))) list_clean(y) # Non-list inputs are returned unchanged list_clean(data.frame(x = 1:3)) list_clean(1:5) list_clean(NULL)#---------------------------------------------------------------------------- # list_clean() examples #---------------------------------------------------------------------------- library(bkbase) # Removes NULL and zero-length elements, preserves names x <- list(a = 1, b = NULL, c = logical(0L), d = 2) list_clean(x) # Recursive cleaning, including fully-empty sublists y <- list(a = list(1, NULL), b = list(NULL, logical(0L))) list_clean(y) # Non-list inputs are returned unchanged list_clean(data.frame(x = 1:3)) list_clean(1:5) list_clean(NULL)
Recursively flattens any nested lists into a single-level list.
Non-list objects are treated as leaves and kept as single elements.
If preserve_df = TRUE, data.frames are treated as leaves and not exploded.
list_flatten2(x, preserve_df = TRUE, keep_names = TRUE)list_flatten2(x, preserve_df = TRUE, keep_names = TRUE)
x |
(list) |
preserve_df |
( |
keep_names |
( |
A single-level list containing all leaf elements from x, in left-to-right order.
#---------------------------------------------------------------------------- # list_flatten2() examples #---------------------------------------------------------------------------- library(bkbase) # Flatten x <- list(1, list(2, list(3, 4)), 5) list_flatten2(x) # Preserves leaf names and data frames as leaves y <- list(list(a = 1:2), data.frame(x = 1:2), list(b = "z")) list_flatten2(y) # Drop leaf names z <- list(list(a = c("name1" = 1, "name2" = 2)), list(b = "z")) list_flatten2(z, keep_names = FALSE)#---------------------------------------------------------------------------- # list_flatten2() examples #---------------------------------------------------------------------------- library(bkbase) # Flatten x <- list(1, list(2, list(3, 4)), 5) list_flatten2(x) # Preserves leaf names and data frames as leaves y <- list(list(a = 1:2), data.frame(x = 1:2), list(b = "z")) list_flatten2(y) # Drop leaf names z <- list(list(a = c("name1" = 1, "name2" = 2)), list(b = "z")) list_flatten2(z, keep_names = FALSE)
Converts logical vectors and matrices to integer type.
Values FALSE, TRUE, and NA are converted to 0, 1, or NA_integer_, respectively.
logical_to_integer(x)logical_to_integer(x)
x |
(logical vector, matrix, or array) |
logical_to_integer() will not drop dimensional attributes (as done by as.integer()).
integer vector, matrix, or array with the same dimensions as x.
#---------------------------------------------------------------------------- # logical_to_integer() examples #---------------------------------------------------------------------------- library(bkbase) logical_to_integer(c(TRUE, FALSE, NA)) logical_to_integer(matrix(c(TRUE, FALSE, TRUE), nrow = 3))#---------------------------------------------------------------------------- # logical_to_integer() examples #---------------------------------------------------------------------------- library(bkbase) logical_to_integer(c(TRUE, FALSE, NA)) logical_to_integer(matrix(c(TRUE, FALSE, TRUE), nrow = 3))
Resolve an argument that takes one string from a fixed set, as base::match.arg() does.
Use match.arg2() at the start of a function whose formal default lists the allowed values, as in link = c("logit", "probit").
match.arg2(arg, choices, name = NULL)match.arg2(arg, choices, name = NULL)
arg |
( |
choices |
( |
name |
( |
match.arg2() is different from base::match.arg() in these ways:
The function accepts only an exact match.
The value "log" does not match "logit".
NULL gives an error.
match.arg() returns the first choice for NULL.
The error message names the argument and states the value that it received, with format_value().
The function has no several.ok argument, and it always returns one choice.
When arg is identical to choices, the function returns the first choice.
The caller gets this result when it does not supply the argument, because the value of arg is then the full default vector.
When choices is missing, the function finds the choices in the default of the formal argument name of the calling function.
It evaluates that default in the frame of the caller.
Because of this, a default can use a constant of the namespace of the caller.
The lookup works only when the caller passes the argument under its formal name, as with match.arg().
For example, l <- link; match.arg2(l) finds no choices, because the caller has no argument l.
In this case, pass choices.
When the formal argument has no default, R stops with the error "argument is missing, with no default", as with match.arg().
The error message for a string that is not a choice states the string, "" included.
For NA_character_, the message states only the choices.
The error has no call, because the call of match.arg2() does not help the user.
character(1), the matched element of choices with no names.
The function stops with an error when arg does not match, or when it finds no choices.
#---------------------------------------------------------------------------- # match.arg2() example #---------------------------------------------------------------------------- library(bkbase) # The formal default lists the choices. No value gives the first choice. fit <- function(link = c("logit", "probit", "cloglog")) { link <- match.arg2(link) link } fit() fit("probit") # A prefix of a choice does not match, and NULL gives an error. try(fit("log")) try(fit(NULL)) # Pass `choices` for a value that is not a formal argument. opts <- list(type = "b") match.arg2(opts$type, c("a", "b"))#---------------------------------------------------------------------------- # match.arg2() example #---------------------------------------------------------------------------- library(bkbase) # The formal default lists the choices. No value gives the first choice. fit <- function(link = c("logit", "probit", "cloglog")) { link <- match.arg2(link) link } fit() fit("probit") # A prefix of a choice does not match, and NULL gives an error. try(fit("log")) try(fit(NULL)) # Pass `choices` for a value that is not a formal argument. opts <- list(type = "b") match.arg2(opts$type, c("a", "b"))
Wraps base::match.call() with two additions.
Argument n selects a call further up the call stack rather than the immediate caller.
Argument defaults = TRUE inserts formal defaults for arguments the caller did not supply.
match.call2( n = 0L, definition = sys.function(sys.parent(n + 1L)), call = sys.call(sys.parent(n + 1L)), expand.dots = TRUE, envir = parent.frame(n + 2L), defaults = FALSE )match.call2( n = 0L, definition = sys.function(sys.parent(n + 1L)), call = sys.call(sys.parent(n + 1L)), expand.dots = TRUE, envir = parent.frame(n + 2L), defaults = FALSE )
n |
( |
definition |
(function; default |
call |
(call; default |
expand.dots |
( |
envir |
(environment; default |
defaults |
( |
An object of class call.
When defaults = TRUE, formal arguments with defaults that the caller did not supply are inserted into the call as unevaluated expressions.
Caller-supplied arguments appear in formal order, as with base::match.call(), and the inserted defaults are appended after them in formal order.
#---------------------------------------------------------------------------- # match.call2() examples #---------------------------------------------------------------------------- library(bkbase) # Basic usage: capture the matched call from within a function. fit <- function(x, y, method = "ols", tol = 1e-8) { match.call2() } fit(1:5, 6:10) # defaults = TRUE inserts unevaluated formal defaults for arguments the # caller did not supply, producing a self-describing call useful for # logging or reproducing results. fit2 <- function(x, y, method = "ols", tol = 1e-8) { match.call2(defaults = TRUE) } fit2(1:5, 6:10) fit2(1:5, 6:10, method = "ridge") # n > 0 reaches further up the call stack, so a helper can inspect how # its caller was invoked. log_caller <- function() match.call2(n = 1) wrapper <- function(a, b = 2) log_caller() wrapper(a = 10) # expand.dots = FALSE keeps the ... arguments grouped under one slot. inspect <- function(x, ...) match.call2(expand.dots = FALSE) inspect(x = 1, extra1 = "a", extra2 = "b")#---------------------------------------------------------------------------- # match.call2() examples #---------------------------------------------------------------------------- library(bkbase) # Basic usage: capture the matched call from within a function. fit <- function(x, y, method = "ols", tol = 1e-8) { match.call2() } fit(1:5, 6:10) # defaults = TRUE inserts unevaluated formal defaults for arguments the # caller did not supply, producing a self-describing call useful for # logging or reproducing results. fit2 <- function(x, y, method = "ols", tol = 1e-8) { match.call2(defaults = TRUE) } fit2(1:5, 6:10) fit2(1:5, 6:10, method = "ridge") # n > 0 reaches further up the call stack, so a helper can inspect how # its caller was invoked. log_caller <- function() match.call2(n = 1) wrapper <- function(a, b = 2) log_caller() wrapper(a = 10) # expand.dots = FALSE keeps the ... arguments grouped under one slot. inspect <- function(x, ...) match.call2(expand.dots = FALSE) inspect(x = 1, extra1 = "a", extra2 = "b")
Return the middle element of an atomic vector after sorting. Missing values are automatically removed.
middle(x)middle(x)
x |
(atomic vector) |
For odd-length input, returns the unique middle element of the sorted vector.
For even-length input, returns the lower of the two middle elements (sort(x)[ceiling(length(x) / 2)]), not the average.
This differs from stats::median() and allows middle() to work on any atomic type, including character and factor inputs.
A scalar of the same type as x.
Empty or all-NA input gives a zero-length vector of that type, and NULL gives NULL.
#---------------------------------------------------------------------------- # middle() example #---------------------------------------------------------------------------- library(bkbase) # Odd-length input returns the single middle element middle(c(1, 2, 3, 4, 5)) # Even-length input returns the lower of the two middle elements middle(c(1, 2, 3, 4)) # Works on any atomic type middle(c("a", "b", "c", "d", "e")) # Missing values are removed before selecting the middle element middle(c(1, 2, 3, NA, NA))#---------------------------------------------------------------------------- # middle() example #---------------------------------------------------------------------------- library(bkbase) # Odd-length input returns the single middle element middle(c(1, 2, 3, 4, 5)) # Even-length input returns the lower of the two middle elements middle(c(1, 2, 3, 4)) # Works on any atomic type middle(c("a", "b", "c", "d", "e")) # Missing values are removed before selecting the middle element middle(c(1, 2, 3, NA, NA))
Compute a position-wise logical OR across multiple logical inputs.
When no TRUE is present, it allows up to a specified fraction of missing values per position before returning NA.
or(..., .na_allowed = 0.2)or(..., .na_allowed = 0.2)
... |
( |
.na_allowed |
( |
Standard logical disjunction over multiple vectors (e.g., x | y | z).
Each output position corresponds to one vector index, or to one row when a matrix or data.frame is supplied.
Returns TRUE for a position if at least one element is TRUE, regardless of missing values.
Returns NA for a position if no TRUE is present and the fraction of NA exceeds .na_allowed.
Otherwise, missing values are treated as FALSE when evaluating the OR.
For each position (row) across inputs, let be the number of NAs and be the number of TRUEs.
Define the missing fraction .
Then:
Notes:
When .na_allowed = 0, behavior matches strict OR: NA propagates only when no TRUE is present.
When , missingness never forces NA.
NAs are treated as FALSE, so the result is TRUE iff any TRUE is present, otherwise FALSE.
A logical vector with values TRUE, FALSE, or NA per the rule in Details.
The length equals the length of each input vector, or the number of rows of a matrix or data.frame.
#---------------------------------------------------------------------------- # or() examples #---------------------------------------------------------------------------- library(bkbase) x <- c(FALSE, FALSE, FALSE, TRUE, FALSE) y <- c(FALSE, FALSE, NA, FALSE, NA) z <- c(FALSE, NA, NA, NA, TRUE) # Base R strict OR x | y | z # NA tolerance at 20% or(x, y, z, .na_allowed = 0.2) # NA tolerance at 40% or(x, y, z, .na_allowed = 0.4) # Single data.frame input df <- data.frame(x = x, y = y, z = z) or(df, .na_allowed = 0.4) # TRUE dominates even when NA is present or(TRUE, NA, .na_allowed = 0)#---------------------------------------------------------------------------- # or() examples #---------------------------------------------------------------------------- library(bkbase) x <- c(FALSE, FALSE, FALSE, TRUE, FALSE) y <- c(FALSE, FALSE, NA, FALSE, NA) z <- c(FALSE, NA, NA, NA, TRUE) # Base R strict OR x | y | z # NA tolerance at 20% or(x, y, z, .na_allowed = 0.2) # NA tolerance at 40% or(x, y, z, .na_allowed = 0.4) # Single data.frame input df <- data.frame(x = x, y = y, z = z) or(df, .na_allowed = 0.4) # TRUE dominates even when NA is present or(TRUE, NA, .na_allowed = 0)
Output written to stdout during the evaluation of x is suppressed.
Messages, warnings, and errors are not suppressed.
quiet(x)quiet(x)
x |
(expression) |
The value of x, returned invisibly.
#---------------------------------------------------------------------------- # quiet() examples #---------------------------------------------------------------------------- library(bkbase) bad_fun <- function(x) { cat("Unwanted output\n") x } # Direct call writes to stdout and returns the value: bad_fun(2) # Wrapped call suppresses stdout and returns invisibly: quiet(bad_fun(2)) # The return value is preserved: result <- quiet(bad_fun(2)) result#---------------------------------------------------------------------------- # quiet() examples #---------------------------------------------------------------------------- library(bkbase) bad_fun <- function(x) { cat("Unwanted output\n") x } # Direct call writes to stdout and returns the value: bad_fun(2) # Wrapped call suppresses stdout and returns invisibly: quiet(bad_fun(2)) # The return value is preserved: result <- quiet(bad_fun(2)) result
base::sample() treats a single numeric x with x >= 1 as 1:x and samples from that sequence.
This surprises callers when x may have varying length, such as in sample(x).
resample() always samples from the elements of x itself.
See base::sample() for more details.
resample(x, size, replace = FALSE, prob = NULL)resample(x, size, replace = FALSE, prob = NULL)
x |
(atomic vector) |
size |
( |
replace |
( |
prob |
( |
When replace = FALSE, size must not exceed length(x).
A vector of length size with elements sampled from x.
#---------------------------------------------------------------------------- # resample() examples #---------------------------------------------------------------------------- library(bkbase) set.seed(2) # Sample without replacement resample(x = 1:10, size = 5) # Sample with replacement resample(x = c("a", "b", "c"), size = 5, replace = TRUE) # Weighted sampling resample( x = c("heads", "tails"), size = 3, replace = TRUE, prob = c(0.7, 0.3) ) # A length-1 vector is sampled as-is, unlike base::sample() resample(x = 5L, size = 1L) sample(x = 5L, size = 1L) # samples from 1:5 instead#---------------------------------------------------------------------------- # resample() examples #---------------------------------------------------------------------------- library(bkbase) set.seed(2) # Sample without replacement resample(x = 1:10, size = 5) # Sample with replacement resample(x = c("a", "b", "c"), size = 5, replace = TRUE) # Weighted sampling resample( x = c("heads", "tails"), size = 3, replace = TRUE, prob = c(0.7, 0.3) ) # A length-1 vector is sampled as-is, unlike base::sample() resample(x = 5L, size = 1L) sample(x = 5L, size = 1L) # samples from 1:5 instead
Quickly reset data frame row names to integers using a pipe-compatible function.
reset_rownames(data) remove_rownames(data)reset_rownames(data) remove_rownames(data)
data |
(data.frame) |
A data frame identical to data except that the row.names attribute is reset to 1:nrow(data).
#---------------------------------------------------------------------------- # reset_rownames() examples #---------------------------------------------------------------------------- library(bkbase) # Subsetting a data frame preserves the original row names. df <- data.frame(a = 1:5) sub <- df[c(3, 5), , drop = FALSE] sub # reset_rownames() renumbers them as 1:nrow(sub). reset_rownames(sub) # remove_rownames() is an alias for reset_rownames(). remove_rownames(sub) # Pipe-compatible. df[c(3, 5), , drop = FALSE] |> reset_rownames()#---------------------------------------------------------------------------- # reset_rownames() examples #---------------------------------------------------------------------------- library(bkbase) # Subsetting a data frame preserves the original row names. df <- data.frame(a = 1:5) sub <- df[c(3, 5), , drop = FALSE] sub # reset_rownames() renumbers them as 1:nrow(sub). reset_rownames(sub) # remove_rownames() is an alias for reset_rownames(). remove_rownames(sub) # Pipe-compatible. df[c(3, 5), , drop = FALSE] |> reset_rownames()
Returns the lengths and values of runs of consecutive equal elements in a vector.
rle2(x, order = FALSE, index = TRUE, na.last = TRUE)rle2(x, order = FALSE, index = TRUE, na.last = TRUE)
x |
(atomic vector) |
order |
( |
index |
( |
na.last |
( |
base::rle() returns a list with a custom print method.
rle2() returns a data.frame, optionally annotated with the start and stop indices of each run, and optionally sorted by value.
Unlike base::rle(), consecutive NAs collapse into a single run.
A transition between NA and a non-NA value also counts as a run boundary.
A zero-length x returns a zero-row data.frame with the documented columns.
The returned data.frame is not compatible with base::inverse.rle().
data.frame with structure:
| Column | Name | Class | Note |
| 1 | value |
class(x) |
|
| 2 | length |
integer |
|
| 3 | start |
integer |
Optional |
| 4 | stop |
integer |
Optional |
#---------------------------------------------------------------------------- # rle2() examples #---------------------------------------------------------------------------- library(bkbase) x <- c(NA, NA, rev(rep(6:10, 1:5)), NA) # base::rle() splits NAs into single-element runs and returns a list. rle(x) # rle2() collapses consecutive NAs and returns a data frame. rle2(x) # Drop the start and stop columns. rle2(x, index = FALSE) # Sort by value. NA runs are placed last by default. rle2(x, order = TRUE) # Sort by value and drop NA runs entirely. rle2(x, order = TRUE, na.last = NA) # Works on any atomic vector, including character. rle2(c("a", "a", "b", "a", "a", "a"))#---------------------------------------------------------------------------- # rle2() examples #---------------------------------------------------------------------------- library(bkbase) x <- c(NA, NA, rev(rep(6:10, 1:5)), NA) # base::rle() splits NAs into single-element runs and returns a list. rle(x) # rle2() collapses consecutive NAs and returns a data frame. rle2(x) # Drop the start and stop columns. rle2(x, index = FALSE) # Sort by value. NA runs are placed last by default. rle2(x, order = TRUE) # Sort by value and drop NA runs entirely. rle2(x, order = TRUE, na.last = NA) # Works on any atomic vector, including character. rle2(c("a", "a", "b", "a", "a", "a"))
Remove missing values from an atomic vector using a pipe-compatible function.
rm_na(x) rmna(x)rm_na(x) rmna(x)
x |
(vector) |
NaN values are also removed because is.na(NaN) returns TRUE.
NULL input returns NULL because anyNA(NULL) is FALSE.
Zero-length input is returned unchanged.
Attributes such as names, factor levels, and Date/POSIXct class are preserved by the [ subset.
A matrix, an array with two or more dimensions, or a data.frame gives an error.
Use stats::na.omit() to remove rows that hold missing values.
A vector of the same type and class as x with NA values removed.
#---------------------------------------------------------------------------- # rm_na() examples #---------------------------------------------------------------------------- library(bkbase) # No NAs: input is returned unchanged rm_na(1:3) # NAs are removed rm_na(c(1, NA, 2, NA, 3)) # NaN is also removed rm_na(c(1, NaN, 2)) # Names and other attributes are preserved rm_na(c(a = 1, b = NA, c = 3)) rm_na(factor(c("a", NA, "b"))) # rmna() is an alias for rm_na() c(1, NA, 2) |> rmna()#---------------------------------------------------------------------------- # rm_na() examples #---------------------------------------------------------------------------- library(bkbase) # No NAs: input is returned unchanged rm_na(1:3) # NAs are removed rm_na(c(1, NA, 2, NA, 3)) # NaN is also removed rm_na(c(1, NaN, 2)) # Names and other attributes are preserved rm_na(c(a = 1, b = NA, c = 3)) rm_na(factor(c("a", NA, "b"))) # rmna() is an alias for rm_na() c(1, NA, 2) |> rmna()
Round the numeric elements of an atomic vector and return a character vector. Elements that do not represent a single number are left unchanged.
round2(x, digits = 3L)round2(x, digits = 3L)
x |
(atomic vector) |
digits |
( |
Each element is coerced to character, then parsed with base::as.numeric().
Elements that parse to a finite number or to Inf/-Inf are rounded to digits decimal places.
All other elements pass through unchanged, including text such as "$99.99", "NaN", and NA.
A nonzero value that rounds to zero loses all magnitude information.
Such values are shown in compact scientific notation (for example "1.0e-04") instead of "0".
Exact zero is returned as "0".
Other results with an absolute value below 1e15 use fixed notation, as in "100000".
The fixed string has the same significant digits as the result of base::as.character(), so both strings give the same number.
Results with an absolute value of 1e15 or more keep the format of base::as.character(), as in "1e+15".
Logical input is rendered as "TRUE"/"FALSE" rather than 0/1.
Names on x are preserved.
A character vector the same length as x.
base::round(),
base::sprintf()
#---------------------------------------------------------------------------- # round2() example #---------------------------------------------------------------------------- library(bkbase) round2(c("hello", "0.0001", "1.23456", "hello 1.23456"))#---------------------------------------------------------------------------- # round2() example #---------------------------------------------------------------------------- library(bkbase) round2(c("hello", "0.0001", "1.23456", "hello 1.23456"))
Compute the cumulative sums along each row of a matrix.
Column of the result holds the sum of columns 1 to of x.
For example, rowCumsums() changes a matrix of category probabilities into cumulative probabilities.
rowCumsums(x)rowCumsums(x)
x |
(numeric or logical matrix) |
The result in row and column is:
The function adds each column to the column before it, from left to right.
An NA or NaN in column gives NA or NaN in column and in each column to its right.
The columns to its left keep their values.
R does not specify which of NA and NaN a sum of the two gives (see base::NaN).
Inf and -Inf are values, and their sum is NaN.
A double matrix gives a double matrix, with sums in double precision.
base::cumsum() keeps its running sum in long double when the platform supports it.
Because of this, the results of rowCumsums(x) and t(apply(x, 1, cumsum)) can differ in the last bits.
An integer or a logical matrix gives an integer matrix.
The function counts FALSE as 0 and TRUE as 1.
A sum larger than .Machine$integer.max gives NA with a warning, as integer addition does.
To prevent this, convert x to double first.
A numeric matrix with zero or one column returns unchanged. A matrix with zero rows returns with its dimensions.
A matrix with the dimensions and the dimnames of x.
The type is integer when x is integer or logical, and double otherwise.
Other rowwise:
rowMaxs(),
rowMaxs2(),
rowMeans2(),
rowSums2()
#---------------------------------------------------------------------------- # rowCumsums() example #---------------------------------------------------------------------------- library(bkbase) # Change category probabilities into cumulative probabilities. p <- matrix( c(0.2, 0.5, 0.3, 0.1, 0.1, 0.8), nrow = 2, byrow = TRUE, dimnames = list(NULL, c("low", "mid", "high")) ) rowCumsums(p) # An NA changes its column and the columns to its right. rowCumsums(matrix(c(1, NA, 3, 4), nrow = 1))#---------------------------------------------------------------------------- # rowCumsums() example #---------------------------------------------------------------------------- library(bkbase) # Change category probabilities into cumulative probabilities. p <- matrix( c(0.2, 0.5, 0.3, 0.1, 0.1, 0.8), nrow = 2, byrow = TRUE, dimnames = list(NULL, c("low", "mid", "high")) ) rowCumsums(p) # An NA changes its column and the columns to its right. rowCumsums(matrix(c(1, NA, 3, 4), nrow = 1))
Compute row-wise maxima from a logical/numeric matrix or data.frame. Optionally ignore missing values. Row names are preserved on ordinary non-empty results.
rowMaxs(x, na.rm = FALSE)rowMaxs(x, na.rm = FALSE)
x |
(logical/numeric matrix or data.frame) |
na.rm |
( |
Let be the number of columns in x.
For row , define the row-wise maximum as follows.
If na.rm = TRUE, the maximum is computed over the observed values only.
NaN is treated as missing because missingness is determined by base::is.na().
If all entries in row are missing, the returned value for that row is NA.
If na.rm = FALSE, the maximum includes missing values.
In this case, any NA present in row yields an NA result for that row.
Inf and -Inf are treated as observed values and can be returned as row maxima.
Logical values are evaluated as FALSE = 0 and TRUE = 1.
If x has row names, those names are assigned to the resulting vector.
A vector of length nrow(x) containing the row-wise maxima.
The storage type is integer when x is integer or logical, and double otherwise.
If x has zero rows, a zero-length vector of the appropriate storage type is returned.
If x has zero columns, an unnamed length-nrow(x) vector of NA of the appropriate storage type is returned.
Rows return NA according to the rules described by na.rm.
For inputs with at least one row and one column, row names are preserved when present.
Other rowwise:
rowCumsums(),
rowMaxs2(),
rowMeans2(),
rowSums2()
#---------------------------------------------------------------------------- # rowMaxs() examples #---------------------------------------------------------------------------- library(bkbase) # Example matrix m <- matrix( c(1, NA, 3, 4, 2, 5, NA, 6), nrow = 2, byrow = TRUE ) m # Row-wise maxima without removing NAs (rows containing NA yield NA) rowMaxs(m, na.rm = FALSE) # Row-wise maxima removing NAs rowMaxs(m, na.rm = TRUE) # Row names are preserved on ordinary non-empty results rownames(m) <- c("row_a", "row_b") rowMaxs(m, na.rm = TRUE)#---------------------------------------------------------------------------- # rowMaxs() examples #---------------------------------------------------------------------------- library(bkbase) # Example matrix m <- matrix( c(1, NA, 3, 4, 2, 5, NA, 6), nrow = 2, byrow = TRUE ) m # Row-wise maxima without removing NAs (rows containing NA yield NA) rowMaxs(m, na.rm = FALSE) # Row-wise maxima removing NAs rowMaxs(m, na.rm = TRUE) # Row names are preserved on ordinary non-empty results rownames(m) <- c("row_a", "row_b") rowMaxs(m, na.rm = TRUE)
Compute row-wise maxima from a logical/numeric matrix or data.frame.
Rows exceeding a specified missing-value proportion are set to NA.
Row names are preserved on ordinary non-empty results.
rowMaxs2(x, na_allowed = 0.2)rowMaxs2(x, na_allowed = 0.2)
x |
(logical/numeric matrix or data.frame) |
na_allowed |
( |
For row , let be the proportion of missing values in that row.
If where is na_allowed, the returned maximum for row is NA.
Otherwise, the maximum is computed over the observed values only:
If all entries in a row are NA, the result for that row is NA regardless of na_allowed.
NaN is treated as missing because missingness is determined by base::is.na().
It counts toward and is excluded from the maximum.
Inf and -Inf are treated as observed values and can be returned as row maxima.
Logical values are evaluated as FALSE = 0 and TRUE = 1.
If x has row names, those names are assigned to the resulting vector.
A vector of length nrow(x) containing the row-wise maxima, with NA where the missing proportion exceeds na_allowed.
The storage type is integer when x is integer or logical, and double otherwise.
If x has zero rows, a zero-length vector of the appropriate storage type is returned.
If x has zero columns, an unnamed length-nrow(x) vector of NA of the appropriate storage type is returned.
For inputs with at least one row and one column, row names are preserved when present.
Other rowwise:
rowCumsums(),
rowMaxs(),
rowMeans2(),
rowSums2()
#---------------------------------------------------------------------------- # rowMaxs2() examples #---------------------------------------------------------------------------- library(bkbase) # Example matrix m <- matrix( c(1, NA, 3, 4, 2, 5, NA, 6), nrow = 2, byrow = TRUE ) m # Allow up to 25% missing per row: both rows are computed rowMaxs2(m, na_allowed = 0.25) # Tighten allowance to 0%: any row with an NA becomes NA rowMaxs2(m, na_allowed = 0) # Row names are preserved on ordinary non-empty results rownames(m) <- c("row_a", "row_b") rowMaxs2(m, na_allowed = 0.5)#---------------------------------------------------------------------------- # rowMaxs2() examples #---------------------------------------------------------------------------- library(bkbase) # Example matrix m <- matrix( c(1, NA, 3, 4, 2, 5, NA, 6), nrow = 2, byrow = TRUE ) m # Allow up to 25% missing per row: both rows are computed rowMaxs2(m, na_allowed = 0.25) # Tighten allowance to 0%: any row with an NA becomes NA rowMaxs2(m, na_allowed = 0) # Row names are preserved on ordinary non-empty results rownames(m) <- c("row_a", "row_b") rowMaxs2(m, na_allowed = 0.5)
Compute row-wise means from a logical/numeric matrix or data.frame.
Rows exceeding a specified missing-value proportion are set to NA.
rowMeans2(x, na_allowed = 0.2, round_digits = NULL)rowMeans2(x, na_allowed = 0.2, round_digits = NULL)
x |
(logical/numeric matrix or data.frame) |
na_allowed |
( |
round_digits |
( |
Let be the number of columns in x.
For row , let be the proportion of missing values in that row.
If where is na_allowed, the returned mean for row is NA.
Otherwise, when at least one observed value exists, the mean is computed over the observed values only:
If all entries in a row are NA or NaN, the result for that row is NA regardless of na_allowed.
NaN is treated as missing because missingness is determined by base::is.na().
Inf and -Inf are treated as observed values and are passed to base::rowMeans() arithmetic.
A row with both observed Inf and -Inf can therefore return NaN.
Logical values are averaged as FALSE = 0 and TRUE = 1.
Rounding is disabled by default.
Set round_digits to round the resulting means.
A double vector of length nrow(x) containing the row-wise means, with NA where the missing proportion exceeds na_allowed.
For inputs with at least one row and one column, row names are preserved.
If x has zero rows, a zero-length double vector is returned.
If x has zero columns, an unnamed length-nrow(x) double vector of NA is returned.
Other rowwise:
rowCumsums(),
rowMaxs(),
rowMaxs2(),
rowSums2()
#---------------------------------------------------------------------------- # rowMeans2() examples #---------------------------------------------------------------------------- library(bkbase) m <- matrix( c(1, NA, 3, 4, 2, 5, NA, 6), nrow = 2, byrow = TRUE ) m # Allow up to 25% missing per row rowMeans2(m, na_allowed = 0.25) # Enable rounding to 2 digits rowMeans2(m, na_allowed = 0.5, round_digits = 2)#---------------------------------------------------------------------------- # rowMeans2() examples #---------------------------------------------------------------------------- library(bkbase) m <- matrix( c(1, NA, 3, 4, 2, 5, NA, 6), nrow = 2, byrow = TRUE ) m # Allow up to 25% missing per row rowMeans2(m, na_allowed = 0.25) # Enable rounding to 2 digits rowMeans2(m, na_allowed = 0.5, round_digits = 2)
Compute row-wise sums from a logical/numeric matrix or data.frame.
Rows exceeding a specified missing-value proportion are set to NA.
Optionally impute missing values using the row mean when the proportion of missing values does not exceed the specified threshold.
rowSums2(x, na_allowed = 0.2, mean_impute = FALSE, round_digits = NULL)rowSums2(x, na_allowed = 0.2, mean_impute = FALSE, round_digits = NULL)
x |
(logical/numeric matrix or data.frame) |
na_allowed |
( |
mean_impute |
( |
round_digits |
( |
Let be the number of columns in x.
For row , let be the proportion of missing values in that row.
If where is na_allowed, the returned sum for row is NA.
Otherwise:
when mean_impute = FALSE.
when mean_impute = TRUE, where is the mean of the non-missing values in row .
If all entries in a row are NA or NaN, the row has no observed mean.
With mean_impute = TRUE, such rows return NA even when na_allowed = 1.
With mean_impute = FALSE, such rows return 0 when allowed by na_allowed, matching base::rowSums() with na.rm = TRUE.
NaN is treated as missing because missingness is determined by base::is.na().
Inf and -Inf are treated as observed values and are passed to base::rowSums() arithmetic.
A row with both observed Inf and -Inf can therefore return NaN.
Logical values are summed as FALSE = 0 and TRUE = 1.
Rounding is disabled by default.
Set round_digits to round the resulting sums.
A double vector of length nrow(x) containing the row-wise sums, with NA where the missing proportion exceeds na_allowed.
For inputs with at least one row and one column, row names are preserved.
If x has zero rows, a zero-length double vector is returned.
If x has zero columns, an unnamed length-nrow(x) double vector of NA is returned.
Other rowwise:
rowCumsums(),
rowMaxs(),
rowMaxs2(),
rowMeans2()
#---------------------------------------------------------------------------- # rowSums2() examples #---------------------------------------------------------------------------- library(bkbase) m <- matrix( c(1, NA, 3, 4, 2, 5, NA, 6), nrow = 2, byrow = TRUE ) m # No imputation, allow up to 25% missing per row rowSums2(m, na_allowed = 0.25, mean_impute = FALSE) # Mean imputation for rows with some missing but within threshold rowSums2(m, na_allowed = 0.5, mean_impute = TRUE) # Enable rounding to 0 digits rowSums2(m, na_allowed = 0.5, mean_impute = TRUE, round_digits = 0)#---------------------------------------------------------------------------- # rowSums2() examples #---------------------------------------------------------------------------- library(bkbase) m <- matrix( c(1, NA, 3, 4, 2, 5, NA, 6), nrow = 2, byrow = TRUE ) m # No imputation, allow up to 25% missing per row rowSums2(m, na_allowed = 0.25, mean_impute = FALSE) # Mean imputation for rows with some missing but within threshold rowSums2(m, na_allowed = 0.5, mean_impute = TRUE) # Enable rounding to 0 digits rowSums2(m, na_allowed = 0.5, mean_impute = TRUE, round_digits = 0)
Similar to seq.int, but returns an empty vector (integer(0)) if the starting point is larger than the end point.
seq2(from, to)seq2(from, to)
from |
( |
to |
( |
Safer than using something like from:to or seq.int in a programming scenario.
integer().
base::seq.int(),
base::seq(),
base::seq_len(),
base::seq_along()
#---------------------------------------------------------------------------- # seq2() examples #---------------------------------------------------------------------------- library(bkbase) seq2(from = 1, to = 5) seq2(from = 1, to = 1) seq2(from = 1, to = 0)#---------------------------------------------------------------------------- # seq2() examples #---------------------------------------------------------------------------- library(bkbase) seq2(from = 1, to = 5) seq2(from = 1, to = 1) seq2(from = 1, to = 0)
Removes whitespace from the left and right sides of a string.
str_trim2(x, whitespace = "[ \t\r\n]")str_trim2(x, whitespace = "[ \t\r\n]")
x |
( |
whitespace |
( |
NULL is returned as character(0L).
character().
#---------------------------------------------------------------------------- # str_trim2() examples #---------------------------------------------------------------------------- library(bkbase) x <- " example " str_trim2(x) str_trim2(c(" a ", "\tb\n", NA)) str_trim2("--x--", whitespace = "-")#---------------------------------------------------------------------------- # str_trim2() examples #---------------------------------------------------------------------------- library(bkbase) x <- " example " str_trim2(x) str_trim2(c(" a ", "\tb\n", NA)) str_trim2("--x--", whitespace = "-")