| 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-06-10 07:18:18 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 |
(logical) |
na.rm |
(Scalar logical: |
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.
Scalar logical
#---------------------------------------------------------------------------- # 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)
... |
Logical vectors of equal length, or a single logical matrix/data.frame.
Matrix/data.frame inputs must have at least one column.
Inputs are coerced to logical via |
.na_allowed |
(Scalar numeric: |
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.
#---------------------------------------------------------------------------- # 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 |
(logical) |
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.
Scalar logical
#---------------------------------------------------------------------------- # 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)
Coerce's input to missing values (NA) of the same type.
as_na(x)as_na(x)
x |
(object) |
Object of same class as x.
#---------------------------------------------------------------------------- # 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"))
Converts an atomic vector into a string of comma separated elements.
csw( x, n = Inf, quote = TRUE, ellipsis = TRUE, and = FALSE, or = FALSE, period = FALSE, width = 70L )csw( x, n = Inf, quote = TRUE, ellipsis = TRUE, and = FALSE, or = FALSE, period = FALSE, width = 70L )
x |
(atomic vector) |
n |
(scalar integer: |
quote |
(scalar logical: |
ellipsis |
(scalar logical: |
and |
(scalar logical: |
or |
(scalar logical: |
period |
(scalar logical: |
width |
(scalar integer: |
Elements are coerced to character with as.character().
Pre-format numeric values that require specific precision before passing to csw().
When and = TRUE or or = TRUE with three or more elements, a comma is included before the connector (Oxford-comma style), e.g. "a, b, and c".
With exactly two elements, no comma is used, e.g. "a and b".
The period added by period = TRUE is appended after word wrapping, so the final line may exceed width by one character.
A character vector of length 0 or 1.
#---------------------------------------------------------------------------- # csw() example #---------------------------------------------------------------------------- library(bkbase) set.seed(1) csw(letters) c( "Lorem","ipsum","dolor","sit","amet","consectetur","adipiscing","elit", "sed","do","eiusmod","tempor","incididunt","ut","labore","et","dolore", "magna","aliqua","Ut","enim","ad","minim","veniam","quis","nostrud" ) |> csw() |> message() rnorm(30) |> round(digits = 1) |> csw(quote = FALSE, and = TRUE) |> message()#---------------------------------------------------------------------------- # csw() example #---------------------------------------------------------------------------- library(bkbase) set.seed(1) csw(letters) c( "Lorem","ipsum","dolor","sit","amet","consectetur","adipiscing","elit", "sed","do","eiusmod","tempor","incididunt","ut","labore","et","dolore", "magna","aliqua","Ut","enim","ad","minim","veniam","quis","nostrud" ) |> csw() |> message() rnorm(30) |> round(digits = 1) |> csw(quote = FALSE, and = TRUE) |> message()
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 to capture. |
.names |
(Scalar logical: |
.duplicate_names |
(Scalar character: |
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 |
(integer: 500L) |
... |
Further arguments passed to |
character vector
#---------------------------------------------------------------------------- # 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 |
(string) |
env |
(environment: |
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) |
Scalar numeric
#---------------------------------------------------------------------------- # 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 |
(numeric) |
is_sorted |
(Scalar logical: |
Scalar numeric
#---------------------------------------------------------------------------- # 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) |
Scalar integer
#---------------------------------------------------------------------------- # 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) |
Scalar integer
#---------------------------------------------------------------------------- # fnrow() examples #---------------------------------------------------------------------------- library(bkbase) x <- data.frame(a = 1) fnrow(x)#---------------------------------------------------------------------------- # fnrow() examples #---------------------------------------------------------------------------- library(bkbase) x <- data.frame(a = 1) fnrow(x)
A fast, unsafe alternative to base::outer().
fouter(x, y, fun)fouter(x, y, fun)
x |
(atomic vector) |
y |
(atomic vector) |
fun |
(function) |
A matrix with length(x) rows and length(y) columns.
Values are returned by fun() after pairwise expansion of x and y.
#---------------------------------------------------------------------------- # fouter() example #---------------------------------------------------------------------------- library(bkbase) x <- c(1, 2) y <- c(3, 4) fouter(x, y, `+`)#---------------------------------------------------------------------------- # fouter() example #---------------------------------------------------------------------------- library(bkbase) x <- c(1, 2) y <- c(3, 4) fouter(x, y, `+`)
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) |
Scalar numeric
#---------------------------------------------------------------------------- # 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 |
(character vector) |
width |
(Scalar numeric: |
indent |
(Scalar numeric: |
exdent |
(Scalar numeric: |
keep_newlines |
(Scalar logical: |
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 |
(Scalar logical: |
base::tabulate() only counts positive integers.
ftabulate() will count any nonmissing element type.
Integer vector
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) |
Scalar numeric
#---------------------------------------------------------------------------- # 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 )
... |
(character) |
.env |
(environment, list, or data.frame: |
.open, .close
|
(one-character string: |
.sep |
(string: |
.eval |
(Scalar logical: |
Character vector
This function was modified from 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.
Scalar logical.
#---------------------------------------------------------------------------- # 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.
Scalar logical.
#---------------------------------------------------------------------------- # 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 |
The object to be tested. |
Scalar logical
#---------------------------------------------------------------------------- # is_date() examples #---------------------------------------------------------------------------- library(bkbase) d <- as.Date("2019-01-01") dt <- as.POSIXct("2019-01-01") is_datetime(d) is_datetime(dt)#---------------------------------------------------------------------------- # is_date() examples #---------------------------------------------------------------------------- library(bkbase) d <- as.Date("2019-01-01") dt <- as.POSIXct("2019-01-01") is_datetime(d) is_datetime(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 |
The object to be tested. |
Scalar logical
#---------------------------------------------------------------------------- # 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 |
The object to be tested. |
Scalar logical
#---------------------------------------------------------------------------- # 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 |
The object to be tested. |
Scalar logical
#---------------------------------------------------------------------------- # 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 |
The object to be tested. |
Scalar logical
#---------------------------------------------------------------------------- # 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 a 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 |
(numeric) |
na.rm |
(scalar logical) |
Scalar logical
#---------------------------------------------------------------------------- # 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 a 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 |
(numeric) |
na.rm |
(scalar logical) |
Scalar logical
#---------------------------------------------------------------------------- # 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 |
The object to be tested. |
Scalar logical
#---------------------------------------------------------------------------- # 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 |
The object to be tested. |
Scalar logical
#---------------------------------------------------------------------------- # 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 |
The object to be tested. |
Scalar logical
#---------------------------------------------------------------------------- # 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 |
The object to be tested. |
Scalar logical
#---------------------------------------------------------------------------- # 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 |
The object to be tested. |
Scalar logical
#---------------------------------------------------------------------------- # 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 |
The object to be tested. |
Scalar logical
#---------------------------------------------------------------------------- # 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 |
The object to be tested. |
Scalar logical
#---------------------------------------------------------------------------- # 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 |
The object to be tested. |
Scalar logical
#---------------------------------------------------------------------------- # 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 |
The object to be tested. |
Scalar logical
#---------------------------------------------------------------------------- # 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 |
The object to be tested. |
Scalar logical
#---------------------------------------------------------------------------- # 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 |
The object to be tested. |
Scalar logical
#---------------------------------------------------------------------------- # 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 |
The object to be tested. |
tol |
(Scalar numeric: |
NA, NaN, Inf, and -Inf return FALSE.
Zero-length input and NULL return FALSE.
Inputs with length other than 1 return FALSE.
Scalar logical
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 |
The object to be tested. |
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.
Scalar logical
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 |
(numeric) |
na.rm |
(scalar logical) |
Scalar logical
#---------------------------------------------------------------------------- # 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 |
(numeric) |
na.rm |
(scalar logical) |
Scalar logical
#---------------------------------------------------------------------------- # 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 |
The object to be tested. |
Scalar logical
#---------------------------------------------------------------------------- # 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 |
The object to be tested. |
tol |
(Scalar numeric: |
NA, NaN, Inf, and -Inf return FALSE.
Zero-length input and NULL return FALSE.
Scalar logical
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 |
The object to be tested. |
Inf and -Inf in double storage return TRUE because Inf == trunc(Inf).
NA and NaN return FALSE.
Zero-length input and NULL return FALSE.
Scalar logical
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 |
(Scalar logical) |
keep_names |
(Scalar logical) |
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, for 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))
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 |
(Scalar integer: |
definition |
(function: |
call |
(call: |
expand.dots |
(Scalar logical: |
envir |
(environment: |
defaults |
(Scalar logical: |
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 retain their positions, 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 |
An 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.
#---------------------------------------------------------------------------- # 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)
... |
Logical vectors of equal length, or a single logical matrix/data.frame.
Matrix/data.frame inputs must have at least one column.
Inputs are coerced to logical via |
.na_allowed |
(Scalar numeric: |
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.
#---------------------------------------------------------------------------- # 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 are suppressed.
Messages, warnings, and errors are not suppressed.
quiet(x)quiet(x)
x |
An 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 |
(Scalar integer: |
replace |
(Scalar logical) |
prob |
(numeric: |
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 |
(Scalar logical) |
index |
(Scalar logical) |
na.last |
(Scalar logical: |
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 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 |
(scalar whole number: |
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".
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 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 |
(Scalar logical: |
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:
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 |
(Scalar numeric: |
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:
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 |
(Scalar numeric: |
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:
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 |
(Scalar numeric: |
mean_impute |
(Scalar logical: |
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:
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 |
(Scalar integer) |
to |
(Scalar integer) |
Safer than using something like from:to or seq.int in a programming scenario.
Integer vector
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 |
(character) |
whitespace |
(string: |
NULL is returned as character(0L).
character vector
#---------------------------------------------------------------------------- # 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 = "-")