content
stringlengths 0
14.9M
| filename
stringlengths 44
136
|
---|---|
#' FAQ - How is the compatibility of vector types decided?
#'
#' @includeRmd man/faq/user/faq-compatibility-types.Rmd description
#'
#' @name faq-compatibility-types
NULL
#' FAQ - Error/Warning: Some attributes are incompatible
#'
#' @description
#'
#' This error occurs when [vec_ptype2()] or [vec_cast()] are supplied
#' vectors of the same classes with different attributes. In this
#' case, vctrs doesn't know how to combine the inputs.
#'
#' To fix this error, the maintainer of the class should implement
#' self-to-self coercion methods for [vec_ptype2()] and [vec_cast()].
#'
#' @includeRmd man/faq/developer/links-coercion.Rmd
#'
#' @name faq-error-incompatible-attributes
NULL
#' FAQ - Error: Input must be a vector
#'
#' @includeRmd man/faq/user/faq-error-scalar-type.Rmd description
#'
#' @name faq-error-scalar-type
NULL
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/faq.R
|
#' Tools for accessing the fields of a record.
#'
#' A [rcrd] behaves like a vector, so `length()`, `names()`, and `$` can
#' not provide access to the fields of the underlying list. These helpers do:
#' `fields()` is equivalent to `names()`; `n_fields()` is equivalent to
#' `length()`; `field()` is equivalent to `$`.
#'
#' @param x A [rcrd], i.e. a list of equal length vectors with unique names.
#' @keywords internal
#' @export
#' @examples
#' x <- new_rcrd(list(x = 1:3, y = 3:1, z = letters[1:3]))
#' n_fields(x)
#' fields(x)
#'
#' field(x, "y")
#' field(x, "y") <- runif(3)
#' field(x, "y")
fields <- function(x) {
.Call(vctrs_fields, x)
}
#' @export
#' @rdname fields
n_fields <- function(x) {
.Call(vctrs_n_fields, x)
}
#' @export
#' @rdname fields
field <- function(x, i) {
.Call(vctrs_field_get, x, i)
}
#' @export
#' @rdname fields
`field<-` <- function(x, i, value) {
.Call(vctrs_field_set, x, i, value)
}
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/fields.R
|
#' Fill in missing values with the previous or following value
#'
#' @description
#' `r lifecycle::badge("experimental")`
#'
#' `vec_fill_missing()` fills gaps of missing values with the previous or
#' following non-missing value.
#'
#' @param x A vector
#' @param direction Direction in which to fill missing values. Must be either
#' `"down"`, `"up"`, `"downup"`, or `"updown"`.
#' @param max_fill A single positive integer specifying the maximum number of
#' sequential missing values that will be filled. If `NULL`, there is
#' no limit.
#'
#' @export
#' @examples
#' x <- c(NA, NA, 1, NA, NA, NA, 3, NA, NA)
#'
#' # Filling down replaces missing values with the previous non-missing value
#' vec_fill_missing(x, direction = "down")
#'
#' # To also fill leading missing values, use `"downup"`
#' vec_fill_missing(x, direction = "downup")
#'
#' # Limit the number of sequential missing values to fill with `max_fill`
#' vec_fill_missing(x, max_fill = 1)
#'
#' # Data frames are filled rowwise. Rows are only considered missing
#' # if all elements of that row are missing.
#' y <- c(1, NA, 2, NA, NA, 3, 4, NA, 5)
#' df <- data_frame(x = x, y = y)
#' df
#'
#' vec_fill_missing(df)
vec_fill_missing <- function(x,
direction = c("down", "up", "downup", "updown"),
max_fill = NULL) {
.Call(vctrs_fill_missing, x, direction, max_fill)
}
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/fill.R
|
#' Identify groups
#'
#' @description
#'
#' `r lifecycle::badge("experimental")`
#'
#' * `vec_group_id()` returns an identifier for the group that each element of
#' `x` falls in, constructed in the order that they appear. The number of
#' groups is also returned as an attribute, `n`.
#'
#' * `vec_group_loc()` returns a data frame containing a `key` column with the
#' unique groups, and a `loc` column with the locations of each group in `x`.
#'
#' * `vec_group_rle()` locates groups in `x` and returns them run length
#' encoded in the order that they appear. The return value is a rcrd object
#' with fields for the `group` identifiers and the run `length` of the
#' corresponding group. The number of groups is also returned as an
#' attribute, `n`.
#'
#' @param x A vector
#' @return
#' * `vec_group_id()`: An integer vector with the same size as `x`.
#' * `vec_group_loc()`: A two column data frame with size equal to
#' `vec_size(vec_unique(x))`.
#' * A `key` column of type `vec_ptype(x)`
#' * A `loc` column of type list, with elements of type integer.
#' * `vec_group_rle()`: A `vctrs_group_rle` rcrd object with two integer
#' vector fields: `group` and `length`.
#'
#' Note that when using `vec_group_loc()` for complex types, the default
#' `data.frame` print method will be suboptimal, and you will want to coerce
#' into a tibble to better understand the output.
#' @name vec_group
#'
#' @section Dependencies:
#' - [vec_proxy_equal()]
#'
#' @keywords internal
#' @examples
#' purrr <- c("p", "u", "r", "r", "r")
#' vec_group_id(purrr)
#' vec_group_rle(purrr)
#'
#' groups <- mtcars[c("vs", "am")]
#' vec_group_id(groups)
#'
#' group_rle <- vec_group_rle(groups)
#' group_rle
#'
#' # Access fields with `field()`
#' field(group_rle, "group")
#' field(group_rle, "length")
#'
#' # `vec_group_id()` is equivalent to
#' vec_match(groups, vec_unique(groups))
#'
#' vec_group_loc(mtcars$vs)
#' vec_group_loc(mtcars[c("vs", "am")])
#'
#' if (require("tibble")) {
#' as_tibble(vec_group_loc(mtcars[c("vs", "am")]))
#' }
NULL
#' @rdname vec_group
#' @export
vec_group_id <- function(x) {
.Call(vctrs_group_id, x)
}
#' @rdname vec_group
#' @export
vec_group_loc <- function(x) {
.Call(vctrs_group_loc, x)
}
#' @rdname vec_group
#' @export
vec_group_rle <- function(x) {
.Call(vctrs_group_rle, x)
}
#' @export
format.vctrs_group_rle <- function(x, ...) {
group <- field(x, "group")
length <- field(x, "length")
paste0(group, "x", length)
}
#' @export
obj_print_header.vctrs_group_rle <- function(x, ...) {
size <- vec_size(x)
n <- attr(x, "n")
cat_line("<", vec_ptype_full(x), "[", size, "][n = ", n, "]>")
invisible(x)
}
# For testing
new_group_rle <- function(group, length, n) {
stopifnot(is_integer(group))
stopifnot(is_integer(length))
stopifnot(is_integer(n))
vec_check_size(n, size = 1L)
if (vec_size(group) != vec_size(length)) {
abort("`group` and `length` must have the same size.")
}
new_rcrd(list(group = group, length = length), n = n, class = "vctrs_group_rle")
}
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/group.R
|
# These return raw vectors of hashes. Vector elements are coded with
# 32 bit hashes. Thus, the size of the raw vector of hashes is 4 times
# the size of the input.
vec_hash <- function(x) {
.Call(vctrs_hash, x)
}
obj_hash <- function(x) {
.Call(vctrs_hash_object, x)
}
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/hash.R
|
# Standalone file: do not edit by hand
# Source: <https://github.com/r-lib/rlang/blob/main/R/standalone-linked-version.R>
# ----------------------------------------------------------------------
#
# ---
# repo: r-lib/rlang
# file: standalone-linked-version.R
# last-updated: 2022-05-26
# license: https://unlicense.org
# ---
#
# nocov start
check_linked_version <- local({
# Keep in sync with standalone-downstream-deps.R
howto_reinstall_msg <- function(pkg) {
os <- tolower(Sys.info()[["sysname"]])
if (os == "windows") {
url <- "https://github.com/jennybc/what-they-forgot/issues/62"
c(
i = sprintf("Please update %s to the latest version.", pkg),
i = sprintf("Updating packages on Windows requires precautions:\n <%s>", url)
)
} else {
c(
i = sprintf("Please update %s with `install.packages(\"%s\")` and restart R.", pkg, pkg)
)
}
}
function(pkg, with_rlang = requireNamespace("rlang", quietly = TRUE)) {
ver <- utils::packageVersion(pkg)
ns <- asNamespace(pkg)
linked_ver_ptr <- ns[[paste0(pkg, "_linked_version")]]
if (is.null(linked_ver_ptr)) {
linked_ver <- ""
} else {
# Construct call to avoid NOTE when argument to `.Call()` is not
# statically analysable
linked_ver <- do.call(".Call", list(linked_ver_ptr))
}
if (nzchar(linked_ver) && ver == linked_ver) {
return(invisible(NULL))
}
header <- sprintf("The %s package is not properly installed.", pkg)
if (nzchar(linked_ver)) {
msg <- c(x = sprintf(
"The DLL version (%s) does not correspond to the package version (%s).",
linked_ver,
ver
))
} else {
# Package does not have a version pointer. This happens when DLL
# updating fails for the first version that includes the pointer.
msg <- c(x = "The DLL version does not correspond to the package version.")
}
msg <- c(msg, howto_reinstall_msg(pkg))
if (with_rlang) {
msg <- paste(header, rlang::format_error_bullets(msg), sep = "\n")
rlang::abort(msg)
} else {
msg <- paste(c(header, msg), collapse = "\n")
stop(msg, call. = FALSE)
}
}
})
# nocov end
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/import-standalone-linked-version.R
|
# Standalone file: do not edit by hand
# Source: <https://github.com/r-lib/rlang/blob/main/R/standalone-obj-type.R>
# ----------------------------------------------------------------------
#
# ---
# repo: r-lib/rlang
# file: standalone-obj-type.R
# last-updated: 2022-10-04
# license: https://unlicense.org
# ---
#
# ## Changelog
#
# 2022-10-04:
# - `obj_type_friendly(value = TRUE)` now shows numeric scalars
# literally.
# - `stop_friendly_type()` now takes `show_value`, passed to
# `obj_type_friendly()` as the `value` argument.
#
# 2022-10-03:
# - Added `allow_na` and `allow_null` arguments.
# - `NULL` is now backticked.
# - Better friendly type for infinities and `NaN`.
#
# 2022-09-16:
# - Unprefixed usage of rlang functions with `rlang::` to
# avoid onLoad issues when called from rlang (#1482).
#
# 2022-08-11:
# - Prefixed usage of rlang functions with `rlang::`.
#
# 2022-06-22:
# - `friendly_type_of()` is now `obj_type_friendly()`.
# - Added `obj_type_oo()`.
#
# 2021-12-20:
# - Added support for scalar values and empty vectors.
# - Added `stop_input_type()`
#
# 2021-06-30:
# - Added support for missing arguments.
#
# 2021-04-19:
# - Added support for matrices and arrays (#141).
# - Added documentation.
# - Added changelog.
#
# nocov start
#' Return English-friendly type
#' @param x Any R object.
#' @param value Whether to describe the value of `x`. Special values
#' like `NA` or `""` are always described.
#' @param length Whether to mention the length of vectors and lists.
#' @return A string describing the type. Starts with an indefinite
#' article, e.g. "an integer vector".
#' @noRd
obj_type_friendly <- function(x, value = TRUE) {
if (is_missing(x)) {
return("absent")
}
if (is.object(x)) {
if (inherits(x, "quosure")) {
type <- "quosure"
} else {
type <- paste(class(x), collapse = "/")
}
return(sprintf("a <%s> object", type))
}
if (!is_vector(x)) {
return(.rlang_as_friendly_type(typeof(x)))
}
n_dim <- length(dim(x))
if (!n_dim) {
if (!is_list(x) && length(x) == 1) {
if (is_na(x)) {
return(switch(
typeof(x),
logical = "`NA`",
integer = "an integer `NA`",
double =
if (is.nan(x)) {
"`NaN`"
} else {
"a numeric `NA`"
},
complex = "a complex `NA`",
character = "a character `NA`",
.rlang_stop_unexpected_typeof(x)
))
}
show_infinites <- function(x) {
if (x > 0) {
"`Inf`"
} else {
"`-Inf`"
}
}
str_encode <- function(x, width = 30, ...) {
if (nchar(x) > width) {
x <- substr(x, 1, width - 3)
x <- paste0(x, "...")
}
encodeString(x, ...)
}
if (value) {
if (is.numeric(x) && is.infinite(x)) {
return(show_infinites(x))
}
if (is.numeric(x) || is.complex(x)) {
number <- as.character(round(x, 2))
what <- if (is.complex(x)) "the complex number" else "the number"
return(paste(what, number))
}
return(switch(
typeof(x),
logical = if (x) "`TRUE`" else "`FALSE`",
character = {
what <- if (nzchar(x)) "the string" else "the empty string"
paste(what, str_encode(x, quote = "\""))
},
raw = paste("the raw value", as.character(x)),
.rlang_stop_unexpected_typeof(x)
))
}
return(switch(
typeof(x),
logical = "a logical value",
integer = "an integer",
double = if (is.infinite(x)) show_infinites(x) else "a number",
complex = "a complex number",
character = if (nzchar(x)) "a string" else "\"\"",
raw = "a raw value",
.rlang_stop_unexpected_typeof(x)
))
}
if (length(x) == 0) {
return(switch(
typeof(x),
logical = "an empty logical vector",
integer = "an empty integer vector",
double = "an empty numeric vector",
complex = "an empty complex vector",
character = "an empty character vector",
raw = "an empty raw vector",
list = "an empty list",
.rlang_stop_unexpected_typeof(x)
))
}
}
vec_type_friendly(x)
}
vec_type_friendly <- function(x, length = FALSE) {
if (!is_vector(x)) {
abort("`x` must be a vector.")
}
type <- typeof(x)
n_dim <- length(dim(x))
add_length <- function(type) {
if (length && !n_dim) {
paste0(type, sprintf(" of length %s", length(x)))
} else {
type
}
}
if (type == "list") {
if (n_dim < 2) {
return(add_length("a list"))
} else if (is.data.frame(x)) {
return("a data frame")
} else if (n_dim == 2) {
return("a list matrix")
} else {
return("a list array")
}
}
type <- switch(
type,
logical = "a logical %s",
integer = "an integer %s",
numeric = ,
double = "a double %s",
complex = "a complex %s",
character = "a character %s",
raw = "a raw %s",
type = paste0("a ", type, " %s")
)
if (n_dim < 2) {
kind <- "vector"
} else if (n_dim == 2) {
kind <- "matrix"
} else {
kind <- "array"
}
out <- sprintf(type, kind)
if (n_dim >= 2) {
out
} else {
add_length(out)
}
}
.rlang_as_friendly_type <- function(type) {
switch(
type,
list = "a list",
NULL = "`NULL`",
environment = "an environment",
externalptr = "a pointer",
weakref = "a weak reference",
S4 = "an S4 object",
name = ,
symbol = "a symbol",
language = "a call",
pairlist = "a pairlist node",
expression = "an expression vector",
char = "an internal string",
promise = "an internal promise",
... = "an internal dots object",
any = "an internal `any` object",
bytecode = "an internal bytecode object",
primitive = ,
builtin = ,
special = "a primitive function",
closure = "a function",
type
)
}
.rlang_stop_unexpected_typeof <- function(x, call = caller_env()) {
abort(
sprintf("Unexpected type <%s>.", typeof(x)),
call = call
)
}
#' Return OO type
#' @param x Any R object.
#' @return One of `"bare"` (for non-OO objects), `"S3"`, `"S4"`,
#' `"R6"`, or `"R7"`.
#' @noRd
obj_type_oo <- function(x) {
if (!is.object(x)) {
return("bare")
}
class <- inherits(x, c("R6", "R7_object"), which = TRUE)
if (class[[1]]) {
"R6"
} else if (class[[2]]) {
"R7"
} else if (isS4(x)) {
"S4"
} else {
"S3"
}
}
#' @param x The object type which does not conform to `what`. Its
#' `obj_type_friendly()` is taken and mentioned in the error message.
#' @param what The friendly expected type as a string. Can be a
#' character vector of expected types, in which case the error
#' message mentions all of them in an "or" enumeration.
#' @param show_value Passed to `value` argument of `obj_type_friendly()`.
#' @param ... Arguments passed to [abort()].
#' @inheritParams args_error_context
#' @noRd
stop_input_type <- function(x,
what,
...,
allow_na = FALSE,
allow_null = FALSE,
show_value = TRUE,
arg = caller_arg(x),
call = caller_env()) {
# From standalone-cli.R
cli <- env_get_list(
nms = c("format_arg", "format_code"),
last = topenv(),
default = function(x) sprintf("`%s`", x),
inherit = TRUE
)
if (allow_na) {
what <- c(what, cli$format_code("NA"))
}
if (allow_null) {
what <- c(what, cli$format_code("NULL"))
}
if (length(what)) {
what <- oxford_comma(what)
}
message <- sprintf(
"%s must be %s, not %s.",
cli$format_arg(arg),
what,
obj_type_friendly(x, value = show_value)
)
abort(message, ..., call = call, arg = arg)
}
oxford_comma <- function(chr, sep = ", ", final = "or") {
n <- length(chr)
if (n < 2) {
return(chr)
}
head <- chr[seq_len(n - 1)]
last <- chr[n]
head <- paste(head, collapse = sep)
# Write a or b. But a, b, or c.
if (n > 2) {
paste0(head, sep, final, " ", last)
} else {
paste0(head, " ", final, " ", last)
}
}
# nocov end
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/import-standalone-obj-type.R
|
# Standalone file: do not edit by hand
# Source: <https://github.com/r-lib/rlang/blob/main/R/standalone-purrr.R>
# ----------------------------------------------------------------------
#
# ---
# repo: r-lib/rlang
# file: standalone-purrr.R
# last-updated: 2023-02-23
# license: https://unlicense.org
# ---
#
# This file provides a minimal shim to provide a purrr-like API on top of
# base R functions. They are not drop-in replacements but allow a similar style
# of programming.
#
# ## Changelog
#
# 2023-02-23:
# * Added `list_c()`
#
# 2022-06-07:
# * `transpose()` is now more consistent with purrr when inner names
# are not congruent (#1346).
#
# 2021-12-15:
# * `transpose()` now supports empty lists.
#
# 2021-05-21:
# * Fixed "object `x` not found" error in `imap()` (@mgirlich)
#
# 2020-04-14:
# * Removed `pluck*()` functions
# * Removed `*_cpl()` functions
# * Used `as_function()` to allow use of `~`
# * Used `.` prefix for helpers
#
# nocov start
map <- function(.x, .f, ...) {
.f <- as_function(.f, env = global_env())
lapply(.x, .f, ...)
}
walk <- function(.x, .f, ...) {
map(.x, .f, ...)
invisible(.x)
}
map_lgl <- function(.x, .f, ...) {
.rlang_purrr_map_mold(.x, .f, logical(1), ...)
}
map_int <- function(.x, .f, ...) {
.rlang_purrr_map_mold(.x, .f, integer(1), ...)
}
map_dbl <- function(.x, .f, ...) {
.rlang_purrr_map_mold(.x, .f, double(1), ...)
}
map_chr <- function(.x, .f, ...) {
.rlang_purrr_map_mold(.x, .f, character(1), ...)
}
.rlang_purrr_map_mold <- function(.x, .f, .mold, ...) {
.f <- as_function(.f, env = global_env())
out <- vapply(.x, .f, .mold, ..., USE.NAMES = FALSE)
names(out) <- names(.x)
out
}
map2 <- function(.x, .y, .f, ...) {
.f <- as_function(.f, env = global_env())
out <- mapply(.f, .x, .y, MoreArgs = list(...), SIMPLIFY = FALSE)
if (length(out) == length(.x)) {
set_names(out, names(.x))
} else {
set_names(out, NULL)
}
}
map2_lgl <- function(.x, .y, .f, ...) {
as.vector(map2(.x, .y, .f, ...), "logical")
}
map2_int <- function(.x, .y, .f, ...) {
as.vector(map2(.x, .y, .f, ...), "integer")
}
map2_dbl <- function(.x, .y, .f, ...) {
as.vector(map2(.x, .y, .f, ...), "double")
}
map2_chr <- function(.x, .y, .f, ...) {
as.vector(map2(.x, .y, .f, ...), "character")
}
imap <- function(.x, .f, ...) {
map2(.x, names(.x) %||% seq_along(.x), .f, ...)
}
pmap <- function(.l, .f, ...) {
.f <- as.function(.f)
args <- .rlang_purrr_args_recycle(.l)
do.call("mapply", c(
FUN = list(quote(.f)),
args, MoreArgs = quote(list(...)),
SIMPLIFY = FALSE, USE.NAMES = FALSE
))
}
.rlang_purrr_args_recycle <- function(args) {
lengths <- map_int(args, length)
n <- max(lengths)
stopifnot(all(lengths == 1L | lengths == n))
to_recycle <- lengths == 1L
args[to_recycle] <- map(args[to_recycle], function(x) rep.int(x, n))
args
}
keep <- function(.x, .f, ...) {
.x[.rlang_purrr_probe(.x, .f, ...)]
}
discard <- function(.x, .p, ...) {
sel <- .rlang_purrr_probe(.x, .p, ...)
.x[is.na(sel) | !sel]
}
map_if <- function(.x, .p, .f, ...) {
matches <- .rlang_purrr_probe(.x, .p)
.x[matches] <- map(.x[matches], .f, ...)
.x
}
.rlang_purrr_probe <- function(.x, .p, ...) {
if (is_logical(.p)) {
stopifnot(length(.p) == length(.x))
.p
} else {
.p <- as_function(.p, env = global_env())
map_lgl(.x, .p, ...)
}
}
compact <- function(.x) {
Filter(length, .x)
}
transpose <- function(.l) {
if (!length(.l)) {
return(.l)
}
inner_names <- names(.l[[1]])
if (is.null(inner_names)) {
fields <- seq_along(.l[[1]])
} else {
fields <- set_names(inner_names)
.l <- map(.l, function(x) {
if (is.null(names(x))) {
set_names(x, inner_names)
} else {
x
}
})
}
# This way missing fields are subsetted as `NULL` instead of causing
# an error
.l <- map(.l, as.list)
map(fields, function(i) {
map(.l, .subset2, i)
})
}
every <- function(.x, .p, ...) {
.p <- as_function(.p, env = global_env())
for (i in seq_along(.x)) {
if (!rlang::is_true(.p(.x[[i]], ...))) return(FALSE)
}
TRUE
}
some <- function(.x, .p, ...) {
.p <- as_function(.p, env = global_env())
for (i in seq_along(.x)) {
if (rlang::is_true(.p(.x[[i]], ...))) return(TRUE)
}
FALSE
}
negate <- function(.p) {
.p <- as_function(.p, env = global_env())
function(...) !.p(...)
}
reduce <- function(.x, .f, ..., .init) {
f <- function(x, y) .f(x, y, ...)
Reduce(f, .x, init = .init)
}
reduce_right <- function(.x, .f, ..., .init) {
f <- function(x, y) .f(y, x, ...)
Reduce(f, .x, init = .init, right = TRUE)
}
accumulate <- function(.x, .f, ..., .init) {
f <- function(x, y) .f(x, y, ...)
Reduce(f, .x, init = .init, accumulate = TRUE)
}
accumulate_right <- function(.x, .f, ..., .init) {
f <- function(x, y) .f(y, x, ...)
Reduce(f, .x, init = .init, right = TRUE, accumulate = TRUE)
}
detect <- function(.x, .f, ..., .right = FALSE, .p = is_true) {
.p <- as_function(.p, env = global_env())
.f <- as_function(.f, env = global_env())
for (i in .rlang_purrr_index(.x, .right)) {
if (.p(.f(.x[[i]], ...))) {
return(.x[[i]])
}
}
NULL
}
detect_index <- function(.x, .f, ..., .right = FALSE, .p = is_true) {
.p <- as_function(.p, env = global_env())
.f <- as_function(.f, env = global_env())
for (i in .rlang_purrr_index(.x, .right)) {
if (.p(.f(.x[[i]], ...))) {
return(i)
}
}
0L
}
.rlang_purrr_index <- function(x, right = FALSE) {
idx <- seq_along(x)
if (right) {
idx <- rev(idx)
}
idx
}
list_c <- function(x) {
inject(c(!!!x))
}
# nocov end
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/import-standalone-purrr.R
|
# Standalone file: do not edit by hand
# Source: <https://github.com/r-lib/rlang/blob/main/R/standalone-types-check.R>
# ----------------------------------------------------------------------
#
# ---
# repo: r-lib/rlang
# file: standalone-types-check.R
# last-updated: 2023-02-15
# license: https://unlicense.org
# dependencies: standalone-obj-type.R
# ---
#
# ## Changelog
#
# 2023-02-15:
# - Added `check_logical()`.
#
# - `check_bool()`, `check_number_whole()`, and
# `check_number_decimal()` are now implemented in C.
#
# - For efficiency, `check_number_whole()` and
# `check_number_decimal()` now take a `NULL` default for `min` and
# `max`. This makes it possible to bypass unnecessary type-checking
# and comparisons in the default case of no bounds checks.
#
# 2022-10-07:
# - `check_number_whole()` and `_decimal()` no longer treat
# non-numeric types such as factors or dates as numbers. Numeric
# types are detected with `is.numeric()`.
#
# 2022-10-04:
# - Added `check_name()` that forbids the empty string.
# `check_string()` allows the empty string by default.
#
# 2022-09-28:
# - Removed `what` arguments.
# - Added `allow_na` and `allow_null` arguments.
# - Added `allow_decimal` and `allow_infinite` arguments.
# - Improved errors with absent arguments.
#
#
# 2022-09-16:
# - Unprefixed usage of rlang functions with `rlang::` to
# avoid onLoad issues when called from rlang (#1482).
#
# 2022-08-11:
# - Added changelog.
#
# nocov start
# Scalars -----------------------------------------------------------------
.standalone_types_check_dot_call <- .Call
check_bool <- function(x,
...,
allow_na = FALSE,
allow_null = FALSE,
arg = caller_arg(x),
call = caller_env()) {
if (!missing(x) && .standalone_types_check_dot_call(ffi_standalone_is_bool_1.0.7, x, allow_na, allow_null)) {
return(invisible(NULL))
}
stop_input_type(
x,
c("`TRUE`", "`FALSE`"),
...,
allow_na = allow_na,
allow_null = allow_null,
arg = arg,
call = call
)
}
check_string <- function(x,
...,
allow_empty = TRUE,
allow_na = FALSE,
allow_null = FALSE,
arg = caller_arg(x),
call = caller_env()) {
if (!missing(x)) {
is_string <- .rlang_check_is_string(
x,
allow_empty = allow_empty,
allow_na = allow_na,
allow_null = allow_null
)
if (is_string) {
return(invisible(NULL))
}
}
stop_input_type(
x,
"a single string",
...,
allow_na = allow_na,
allow_null = allow_null,
arg = arg,
call = call
)
}
.rlang_check_is_string <- function(x,
allow_empty,
allow_na,
allow_null) {
if (is_string(x)) {
if (allow_empty || !is_string(x, "")) {
return(TRUE)
}
}
if (allow_null && is_null(x)) {
return(TRUE)
}
if (allow_na && (identical(x, NA) || identical(x, na_chr))) {
return(TRUE)
}
FALSE
}
check_name <- function(x,
...,
allow_null = FALSE,
arg = caller_arg(x),
call = caller_env()) {
if (!missing(x)) {
is_string <- .rlang_check_is_string(
x,
allow_empty = FALSE,
allow_na = FALSE,
allow_null = allow_null
)
if (is_string) {
return(invisible(NULL))
}
}
stop_input_type(
x,
"a valid name",
...,
allow_na = FALSE,
allow_null = allow_null,
arg = arg,
call = call
)
}
IS_NUMBER_true <- 0
IS_NUMBER_false <- 1
IS_NUMBER_oob <- 2
check_number_decimal <- function(x,
...,
min = NULL,
max = NULL,
allow_infinite = TRUE,
allow_na = FALSE,
allow_null = FALSE,
arg = caller_arg(x),
call = caller_env()) {
if (missing(x)) {
exit_code <- IS_NUMBER_false
} else if (0 == (exit_code <- .standalone_types_check_dot_call(
ffi_standalone_check_number_1.0.7,
x,
allow_decimal = TRUE,
min,
max,
allow_infinite,
allow_na,
allow_null
))) {
return(invisible(NULL))
}
.stop_not_number(
x,
...,
exit_code = exit_code,
allow_decimal = TRUE,
min = min,
max = max,
allow_na = allow_na,
allow_null = allow_null,
arg = arg,
call = call
)
}
check_number_whole <- function(x,
...,
min = NULL,
max = NULL,
allow_na = FALSE,
allow_null = FALSE,
arg = caller_arg(x),
call = caller_env()) {
if (missing(x)) {
exit_code <- IS_NUMBER_false
} else if (0 == (exit_code <- .standalone_types_check_dot_call(
ffi_standalone_check_number_1.0.7,
x,
allow_decimal = FALSE,
min,
max,
allow_infinite = FALSE,
allow_na,
allow_null
))) {
return(invisible(NULL))
}
.stop_not_number(
x,
...,
exit_code = exit_code,
allow_decimal = FALSE,
min = min,
max = max,
allow_na = allow_na,
allow_null = allow_null,
arg = arg,
call = call
)
}
.stop_not_number <- function(x,
...,
exit_code,
allow_decimal,
min,
max,
allow_na,
allow_null,
arg,
call) {
if (exit_code == IS_NUMBER_oob) {
min <- min %||% -Inf
max <- max %||% Inf
if (min > -Inf && max < Inf) {
what <- sprintf("a number between %s and %s", min, max)
} else if (x < min) {
what <- sprintf("a number larger than %s", min)
} else if (x > max) {
what <- sprintf("a number smaller than %s", max)
} else {
abort("Unexpected state in OOB check", .internal = TRUE)
}
} else if (allow_decimal) {
what <- "a number"
} else {
what <- "a whole number"
}
stop_input_type(
x,
what,
...,
allow_na = allow_na,
allow_null = allow_null,
arg = arg,
call = call
)
}
check_symbol <- function(x,
...,
allow_null = FALSE,
arg = caller_arg(x),
call = caller_env()) {
if (!missing(x)) {
if (is_symbol(x)) {
return(invisible(NULL))
}
if (allow_null && is_null(x)) {
return(invisible(NULL))
}
}
stop_input_type(
x,
"a symbol",
...,
allow_null = allow_null,
arg = arg,
call = call
)
}
check_arg <- function(x,
...,
allow_null = FALSE,
arg = caller_arg(x),
call = caller_env()) {
if (!missing(x)) {
if (is_symbol(x)) {
return(invisible(NULL))
}
if (allow_null && is_null(x)) {
return(invisible(NULL))
}
}
stop_input_type(
x,
"an argument name",
...,
allow_null = allow_null,
arg = arg,
call = call
)
}
check_call <- function(x,
...,
allow_null = FALSE,
arg = caller_arg(x),
call = caller_env()) {
if (!missing(x)) {
if (is_call(x)) {
return(invisible(NULL))
}
if (allow_null && is_null(x)) {
return(invisible(NULL))
}
}
stop_input_type(
x,
"a defused call",
...,
allow_null = allow_null,
arg = arg,
call = call
)
}
check_environment <- function(x,
...,
allow_null = FALSE,
arg = caller_arg(x),
call = caller_env()) {
if (!missing(x)) {
if (is_environment(x)) {
return(invisible(NULL))
}
if (allow_null && is_null(x)) {
return(invisible(NULL))
}
}
stop_input_type(
x,
"an environment",
...,
allow_null = allow_null,
arg = arg,
call = call
)
}
check_function <- function(x,
...,
allow_null = FALSE,
arg = caller_arg(x),
call = caller_env()) {
if (!missing(x)) {
if (is_function(x)) {
return(invisible(NULL))
}
if (allow_null && is_null(x)) {
return(invisible(NULL))
}
}
stop_input_type(
x,
"a function",
...,
allow_null = allow_null,
arg = arg,
call = call
)
}
check_closure <- function(x,
...,
allow_null = FALSE,
arg = caller_arg(x),
call = caller_env()) {
if (!missing(x)) {
if (is_closure(x)) {
return(invisible(NULL))
}
if (allow_null && is_null(x)) {
return(invisible(NULL))
}
}
stop_input_type(
x,
"an R function",
...,
allow_null = allow_null,
arg = arg,
call = call
)
}
check_formula <- function(x,
...,
allow_null = FALSE,
arg = caller_arg(x),
call = caller_env()) {
if (!missing(x)) {
if (is_formula(x)) {
return(invisible(NULL))
}
if (allow_null && is_null(x)) {
return(invisible(NULL))
}
}
stop_input_type(
x,
"a formula",
...,
allow_null = allow_null,
arg = arg,
call = call
)
}
# Vectors -----------------------------------------------------------------
check_character <- function(x,
...,
allow_null = FALSE,
arg = caller_arg(x),
call = caller_env()) {
if (!missing(x)) {
if (is_character(x)) {
return(invisible(NULL))
}
if (allow_null && is_null(x)) {
return(invisible(NULL))
}
}
stop_input_type(
x,
"a character vector",
...,
allow_null = allow_null,
arg = arg,
call = call
)
}
check_logical <- function(x,
...,
allow_null = FALSE,
arg = caller_arg(x),
call = caller_env()) {
if (!missing(x)) {
if (is_logical(x)) {
return(invisible(NULL))
}
if (allow_null && is_null(x)) {
return(invisible(NULL))
}
}
stop_input_type(
x,
"a logical vector",
...,
allow_null = allow_null,
arg = arg,
call = call
)
}
# nocov end
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/import-standalone-types-check.R
|
#' Group overlapping intervals
#'
#' @description
#' These functions are used to group together any overlaps that are present
#' within a set of vector intervals. When multiple overlapping intervals are
#' grouped together they result in a wider interval containing the smallest
#' `start` and the largest `end` of the overlaps.
#'
#' - `vec_interval_groups()` merges all overlapping intervals found within
#' `start` and `end`. The resulting intervals are known as the interval
#' "groups".
#'
#' - `vec_interval_locate_groups()` returns a two column data frame with a `key`
#' column containing the result of `vec_interval_groups()` and a `loc`
#' list-column containing integer vectors that map each interval in `start` and
#' `end` to the group that it falls in.
#'
#' These functions require that `start < end`. Additionally, intervals are
#' treated as if they are right-open, i.e. `[start, end)`.
#'
#' @section Assumptions:
#' For performance and simplicity, these functions make a few assumptions about
#' `start` and `end` that are not checked internally:
#'
#' - `start < end` must be true, with an exception for missing intervals.
#'
#' - If the i-th observation of `start` is missing, then the i-th observation
#' of `end` must also be missing.
#'
#' - Each observation of `start` and `end` must be either
#' [complete][vec_detect_complete] or [missing][vec_detect_missing]. Partially
#' complete values such as `start = data_frame(x = 1, y = NA)` are not allowed.
#'
#' If any of these assumptions are invalid, then the result is undefined.
#'
#' Developer note: These assumptions stem from the idea that if these functions
#' were in ivs itself, then we could safely make these assumptions in the C
#' code, because the `iv()` helper would assert them for us ahead of time.
#' Trying to re-assert these checks in the C code here is wasteful and makes the
#' code more complex.
#'
#' @inheritParams rlang::args_dots_empty
#'
#' @param start,end
#' A pair of vectors representing the starts and ends of the intervals.
#'
#' It is required that `start < end`.
#'
#' `start` and `end` will be cast to their common type, and must have the same
#' size.
#'
#' @param abutting
#' A single logical controlling whether or not abutting intervals should be
#' grouped together. If `TRUE`, `[a, b)` and `[b, c)` will be grouped.
#'
#' @param missing
#' Handling of missing intervals.
#'
#' - `"group"`: Group all missing intervals together.
#'
#' - `"drop"`: Drop all missing intervals from the result.
#'
#' @return
#' - `vec_interval_groups()` returns a data frame with two columns, `start` and
#' `end`, which contain vectors matching the types of `start` and `end`.
#'
#' - `vec_interval_locate_groups()` returns a data frame with two columns, `key`
#' and `loc`. `key` contains the result of `vec_interval_groups()` and `loc` is
#' a list of integer vectors.
#'
#' @name interval-groups
#'
#' @examples
#' bounds <- data_frame(
#' start = c(1, 2, NA, 5, NA, 9, 12),
#' end = c(5, 3, NA, 6, NA, 12, 14)
#' )
#' bounds
#'
#' # Group overlapping intervals together
#' vec_interval_groups(bounds$start, bounds$end)
#'
#' # You can choose not to group abutting intervals if you want to retain
#' # those boundaries
#' vec_interval_groups(bounds$start, bounds$end, abutting = FALSE)
#'
#' # You can also choose to drop all missing intervals if you don't consider
#' # them part of the result
#' vec_interval_groups(bounds$start, bounds$end, missing = "drop")
#'
#' # You can also locate the groups, which allows you to map each original
#' # interval to its corresponding group
#' vec_interval_locate_groups(bounds$start, bounds$end)
#'
#' @noRd
vec_interval_groups <- function(start,
end,
...,
abutting = TRUE,
missing = "group") {
check_dots_empty0(...)
.Call(ffi_interval_groups, start, end, abutting, missing)
}
#' @noRd
#' @rdname interval-groups
vec_interval_locate_groups <- function(start,
end,
...,
abutting = TRUE,
missing = "group") {
check_dots_empty0(...)
.Call(ffi_interval_locate_groups, start, end, abutting, missing)
}
# ------------------------------------------------------------------------------
#' Interval complement
#'
#' @description
#' `vec_interval_complement()` takes the complement of the intervals defined by
#' `start` and `end`. The complement can also be thought of as the "gaps"
#' between the intervals. By default, the minimum of `start` and the maximum of
#' `end` define the bounds to take the complement over, but this can be adjusted
#' with `lower` and `upper`. Missing intervals are always dropped from the
#' complement.
#'
#' These functions require that `start < end`. Additionally, intervals are
#' treated as if they are right-open, i.e. `[start, end)`.
#'
#' @inheritSection interval-groups Assumptions
#'
#' @inheritParams rlang::args_dots_empty
#'
#' @param start,end
#' A pair of vectors representing the starts and ends of the intervals.
#'
#' It is required that `start < end`.
#'
#' `start` and `end` will be cast to their common type, and must have the same
#' size.
#'
#' @param lower,upper
#' Bounds for the universe over which to compute the complement. These should
#' be singular values with the same type as `start` and `end`.
#'
#' @return
#' A two column data frame with a `start` column containing a vector of the
#' same type as `start` and an `end` column containing a vector of the same
#' type as `end`.
#'
#' @examples
#' x <- data_frame(
#' start = c(10, 0, NA, 3, -5, NA),
#' end = c(12, 5, NA, 6, -2, NA)
#' )
#' x
#'
#' # The complement contains any values from `[-5, 12)` that aren't represented
#' # in these intervals. Missing intervals are dropped.
#' vec_interval_complement(x$start, x$end)
#'
#' # Expand out the "universe" of possible values
#' vec_interval_complement(x$start, x$end, lower = -Inf)
#' vec_interval_complement(x$start, x$end, lower = -Inf, upper = Inf)
#'
#' @noRd
vec_interval_complement <- function(start,
end,
...,
lower = NULL,
upper = NULL) {
check_dots_empty0(...)
.Call(ffi_interval_complement, start, end, lower, upper)
}
# ------------------------------------------------------------------------------
#' Interval containers
#'
#' @description
#' `vec_interval_locate_containers()` locates interval _containers_. Containers
#' are defined as the widest intervals that aren't contained by any other
#' interval. The returned locations will arrange the containers in ascending
#' order.
#'
#' For example, with the following vector of intervals: `[1, 5), [2, 6), [3, 4),
#' [5, 9), [5, 8)`, the containers are: `[1, 5), [2, 6), [5, 9)`. The intervals
#' `[3, 4)` and `[5, 8)` aren't containers because they are completely contained
#' within at least one other interval. Note that containers can partially
#' overlap, i.e. `[1, 5)` and `[2, 6)`, and multiple containers can contain the
#' same intervals, i.e. both `[1, 5)` and `[2, 6)` contain `[3, 4)`.
#'
#' Missing intervals are placed into their own container at the end, separate
#' from all other intervals.
#'
#' These functions require that `start < end`. Additionally, intervals are
#' treated as if they are right-open, i.e. `[start, end)`.
#'
#' @inheritSection interval-groups Assumptions
#'
#' @param start,end
#' A pair of vectors representing the starts and ends of the intervals.
#'
#' It is required that `start < end`.
#'
#' `start` and `end` will be cast to their common type, and must have the same
#' size.
#'
#' @return
#' An integer vector that represents the locations of the containers in `start`
#' and `end`.
#'
#' @examples
#' x <- data_frame(
#' start = c(10, 0, NA, 3, 2, 2, NA, 11),
#' end = c(12, 5, NA, 5, 6, 6, NA, 12)
#' )
#' x
#'
#' loc <- vec_interval_locate_containers(x$start, x$end)
#' loc
#'
#' vec_slice(x, loc)
#'
#' @noRd
vec_interval_locate_containers <- function(start, end) {
.Call(ffi_interval_locate_containers, start, end)
}
# ------------------------------------------------------------------------------
# Experimental shims of interval functions used by other packages (mainly, ivs).
#
# This gives us the freedom to experiment with the signature of these functions
# while being backwards compatible with ivs in the meantime.
#
# We can remove these after:
# - The interval functions are exported
# - ivs updates to use them directly
# - A short deprecation period goes by that allows users time to update their
# version of ivs
exp_vec_interval_groups <- function(start,
end,
...,
abutting = TRUE,
missing = "group") {
vec_interval_groups(
start = start,
end = end,
...,
abutting = abutting,
missing = missing
)
}
exp_vec_interval_locate_groups <- function(start,
end,
...,
abutting = TRUE,
missing = "group") {
vec_interval_locate_groups(
start = start,
end = end,
...,
abutting = abutting,
missing = missing
)
}
exp_vec_interval_complement <- function(start,
end,
...,
lower = NULL,
upper = NULL) {
vec_interval_complement(
start = start,
end = end,
...,
lower = lower,
upper = upper
)
}
exp_vec_interval_locate_containers <- function(start, end) {
vec_interval_locate_containers(
start = start,
end = end
)
}
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/interval.R
|
#' Locate observations matching specified conditions
#'
#' @description
#' `r lifecycle::badge("experimental")`
#'
#' `vec_locate_matches()` is a more flexible version of [vec_match()] used to
#' identify locations where each value of `needles` matches one or multiple
#' values in `haystack`. Unlike `vec_match()`, `vec_locate_matches()` returns
#' all matches by default, and can match on binary conditions other than
#' equality, such as `>`, `>=`, `<`, and `<=`.
#'
#' @details
#' [vec_match()] is identical to (but often slightly faster than):
#'
#' ```
#' vec_locate_matches(
#' needles,
#' haystack,
#' condition = "==",
#' multiple = "first",
#' nan_distinct = TRUE
#' )
#' ```
#'
#' `vec_locate_matches()` is extremely similar to a SQL join between `needles`
#' and `haystack`, with the default being most similar to a left join.
#'
#' Be very careful when specifying match `condition`s. If a condition is
#' misspecified, it is very easy to accidentally generate an exponentially
#' large number of matches.
#'
#' @section Dependencies of `vec_locate_matches()`:
#' - [vec_order_radix()]
#' - [vec_detect_complete()]
#'
#' @inheritParams rlang::args_dots_empty
#' @inheritParams rlang::args_error_context
#' @inheritParams order-radix
#'
#' @param needles,haystack Vectors used for matching.
#'
#' - `needles` represents the vector to search for.
#'
#' - `haystack` represents the vector to search in.
#'
#' Prior to comparison, `needles` and `haystack` are coerced to the same type.
#'
#' @param condition Condition controlling how `needles` should be compared
#' against `haystack` to identify a successful match.
#'
#' - One of: `"=="`, `">"`, `">="`, `"<"`, or `"<="`.
#'
#' - For data frames, a length `1` or `ncol(needles)` character vector
#' containing only the above options, specifying how matching is determined
#' for each column.
#'
#' @param filter Filter to be applied to the matched results.
#'
#' - `"none"` doesn't apply any filter.
#'
#' - `"min"` returns only the minimum haystack value matching the current
#' needle.
#'
#' - `"max"` returns only the maximum haystack value matching the current
#' needle.
#'
#' - For data frames, a length `1` or `ncol(needles)` character vector
#' containing only the above options, specifying a filter to apply to
#' each column.
#'
#' Filters don't have any effect on `"=="` conditions, but are useful for
#' computing "rolling" matches with other conditions.
#'
#' A filter can return multiple haystack matches for a particular needle
#' if the maximum or minimum haystack value is duplicated in `haystack`. These
#' can be further controlled with `multiple`.
#'
#' @param incomplete Handling of missing and [incomplete][vec_detect_complete]
#' values in `needles`.
#'
#' - `"compare"` uses `condition` to determine whether or not a missing value
#' in `needles` matches a missing value in `haystack`. If `condition` is
#' `==`, `>=`, or `<=`, then missing values will match.
#'
#' - `"match"` always allows missing values in `needles` to match missing
#' values in `haystack`, regardless of the `condition`.
#'
#' - `"drop"` drops incomplete values in `needles` from the result.
#'
#' - `"error"` throws an error if any `needles` are incomplete.
#'
#' - If a single integer is provided, this represents the value returned
#' in the `haystack` column for values of `needles` that are incomplete. If
#' `no_match = NA`, setting `incomplete = NA` forces incomplete values in
#' `needles` to be treated like unmatched values.
#'
#' `nan_distinct` determines whether a `NA` is allowed to match a `NaN`.
#'
#' @param no_match Handling of `needles` without a match.
#'
#' - `"drop"` drops `needles` with zero matches from the result.
#'
#' - `"error"` throws an error if any `needles` have zero matches.
#'
#' - If a single integer is provided, this represents the value returned in
#' the `haystack` column for values of `needles` that have zero matches. The
#' default represents an unmatched needle with `NA`.
#'
#' @param remaining Handling of `haystack` values that `needles` never matched.
#'
#' - `"drop"` drops remaining `haystack` values from the result.
#' Typically, this is the desired behavior if you only care when `needles`
#' has a match.
#'
#' - `"error"` throws an error if there are any remaining `haystack`
#' values.
#'
#' - If a single integer is provided (often `NA`), this represents the value
#' returned in the `needles` column for the remaining `haystack` values
#' that `needles` never matched. Remaining `haystack` values are always
#' returned at the end of the result.
#'
#' @param multiple Handling of `needles` with multiple matches. For each needle:
#'
#' - `"all"` returns all matches detected in `haystack`.
#'
#' - `"any"` returns any match detected in `haystack` with no guarantees on
#' which match will be returned. It is often faster than `"first"` and
#' `"last"` if you just need to detect if there is at least one match.
#'
#' - `"first"` returns the first match detected in `haystack`.
#'
#' - `"last"` returns the last match detected in `haystack`.
#'
#' @param relationship Handling of the expected relationship between
#' `needles` and `haystack`. If the expectations chosen from the list below
#' are invalidated, an error is thrown.
#'
#' - `"none"` doesn't perform any relationship checks.
#'
#' - `"one-to-one"` expects:
#' - Each value in `needles` matches at most 1 value in `haystack`.
#' - Each value in `haystack` matches at most 1 value in `needles`.
#'
#' - `"one-to-many"` expects:
#' - Each value in `needles` matches any number of values in `haystack`.
#' - Each value in `haystack` matches at most 1 value in `needles`.
#'
#' - `"many-to-one"` expects:
#' - Each value in `needles` matches at most 1 value in `haystack`.
#' - Each value in `haystack` matches any number of values in `needles`.
#'
#' - `"many-to-many"` expects:
#' - Each value in `needles` matches any number of values in `haystack`.
#' - Each value in `haystack` matches any number of values in `needles`.
#'
#' This performs no checks, and is identical to `"none"`, but is provided to
#' allow you to be explicit about this relationship if you know it exists.
#'
#' - `"warn-many-to-many"` doesn't assume there is any known relationship, but
#' will warn if `needles` and `haystack` have a many-to-many relationship
#' (which is typically unexpected), encouraging you to either take a closer
#' look at your inputs or make this relationship explicit by specifying
#' `"many-to-many"`.
#'
#' `relationship` is applied after `filter` and `multiple` to allow potential
#' multiple matches to be filtered out first.
#'
#' `relationship` doesn't handle cases where there are zero matches. For that,
#' see `no_match` and `remaining`.
#'
#' @param needles_arg,haystack_arg Argument tags for `needles` and `haystack`
#' used in error messages.
#'
#' @return A two column data frame containing the locations of the matches.
#'
#' - `needles` is an integer vector containing the location of
#' the needle currently being matched.
#'
#' - `haystack` is an integer vector containing the location of the
#' corresponding match in the haystack for the current needle.
#'
#' @export
#' @examples
#' x <- c(1, 2, NA, 3, NaN)
#' y <- c(2, 1, 4, NA, 1, 2, NaN)
#'
#' # By default, for each value of `x`, all matching locations in `y` are
#' # returned
#' matches <- vec_locate_matches(x, y)
#' matches
#'
#' # The result can be used to slice the inputs to align them
#' data_frame(
#' x = vec_slice(x, matches$needles),
#' y = vec_slice(y, matches$haystack)
#' )
#'
#' # If multiple matches are present, control which is returned with `multiple`
#' vec_locate_matches(x, y, multiple = "first")
#' vec_locate_matches(x, y, multiple = "last")
#' vec_locate_matches(x, y, multiple = "any")
#'
#' # Use `relationship` to add constraints and error on multiple matches if
#' # they aren't expected
#' try(vec_locate_matches(x, y, relationship = "one-to-one"))
#'
#' # In this case, the `NA` in `y` matches two rows in `x`
#' try(vec_locate_matches(x, y, relationship = "one-to-many"))
#'
#' # By default, `NA` is treated as being identical to `NaN`.
#' # Using `nan_distinct = TRUE` treats `NA` and `NaN` as different values, so
#' # `NA` can only match `NA`, and `NaN` can only match `NaN`.
#' vec_locate_matches(x, y, nan_distinct = TRUE)
#'
#' # If you never want missing values to match, set `incomplete = NA` to return
#' # `NA` in the `haystack` column anytime there was an incomplete value
#' # in `needles`.
#' vec_locate_matches(x, y, incomplete = NA)
#'
#' # Using `incomplete = NA` allows us to enforce the one-to-many relationship
#' # that we couldn't before
#' vec_locate_matches(x, y, relationship = "one-to-many", incomplete = NA)
#'
#' # `no_match` allows you to specify the returned value for a needle with
#' # zero matches. Note that this is different from an incomplete value,
#' # so specifying `no_match` allows you to differentiate between incomplete
#' # values and unmatched values.
#' vec_locate_matches(x, y, incomplete = NA, no_match = 0L)
#'
#' # If you want to require that every `needle` has at least 1 match, set
#' # `no_match` to `"error"`:
#' try(vec_locate_matches(x, y, incomplete = NA, no_match = "error"))
#'
#' # By default, `vec_locate_matches()` detects equality between `needles` and
#' # `haystack`. Using `condition`, you can detect where an inequality holds
#' # true instead. For example, to find every location where `x[[i]] >= y`:
#' matches <- vec_locate_matches(x, y, condition = ">=")
#'
#' data_frame(
#' x = vec_slice(x, matches$needles),
#' y = vec_slice(y, matches$haystack)
#' )
#'
#' # You can limit which matches are returned with a `filter`. For example,
#' # with the above example you can filter the matches returned by `x[[i]] >= y`
#' # down to only the ones containing the maximum `y` value of those matches.
#' matches <- vec_locate_matches(x, y, condition = ">=", filter = "max")
#'
#' # Here, the matches for the `3` needle value have been filtered down to
#' # only include the maximum haystack value of those matches, `2`. This is
#' # often referred to as a rolling join.
#' data_frame(
#' x = vec_slice(x, matches$needles),
#' y = vec_slice(y, matches$haystack)
#' )
#'
#' # In the very rare case that you need to generate locations for a
#' # cross match, where every value of `x` is forced to match every
#' # value of `y` regardless of what the actual values are, you can
#' # replace `x` and `y` with integer vectors of the same size that contain
#' # a single value and match on those instead.
#' x_proxy <- vec_rep(1L, vec_size(x))
#' y_proxy <- vec_rep(1L, vec_size(y))
#' nrow(vec_locate_matches(x_proxy, y_proxy))
#' vec_size(x) * vec_size(y)
#'
#' # By default, missing values will match other missing values when using
#' # `==`, `>=`, or `<=` conditions, but not when using `>` or `<` conditions.
#' # This is similar to how `vec_compare(x, y, na_equal = TRUE)` works.
#' x <- c(1, NA)
#' y <- c(NA, 2)
#'
#' vec_locate_matches(x, y, condition = "<=")
#' vec_locate_matches(x, y, condition = "<")
#'
#' # You can force missing values to match regardless of the `condition`
#' # by using `incomplete = "match"`
#' vec_locate_matches(x, y, condition = "<", incomplete = "match")
#'
#' # You can also use data frames for `needles` and `haystack`. The
#' # `condition` will be recycled to the number of columns in `needles`, or
#' # you can specify varying conditions per column. In this example, we take
#' # a vector of date `values` and find all locations where each value is
#' # between lower and upper bounds specified by the `haystack`.
#' values <- as.Date("2019-01-01") + 0:9
#' needles <- data_frame(lower = values, upper = values)
#'
#' set.seed(123)
#' lower <- as.Date("2019-01-01") + sample(10, 10, replace = TRUE)
#' upper <- lower + sample(3, 10, replace = TRUE)
#' haystack <- data_frame(lower = lower, upper = upper)
#'
#' # (values >= lower) & (values <= upper)
#' matches <- vec_locate_matches(needles, haystack, condition = c(">=", "<="))
#'
#' data_frame(
#' lower = vec_slice(lower, matches$haystack),
#' value = vec_slice(values, matches$needle),
#' upper = vec_slice(upper, matches$haystack)
#' )
vec_locate_matches <- function(needles,
haystack,
...,
condition = "==",
filter = "none",
incomplete = "compare",
no_match = NA_integer_,
remaining = "drop",
multiple = "all",
relationship = "none",
nan_distinct = FALSE,
chr_proxy_collate = NULL,
needles_arg = "needles",
haystack_arg = "haystack",
error_call = current_env()) {
check_dots_empty0(...)
frame <- environment()
.Call(
ffi_locate_matches,
needles,
haystack,
condition,
filter,
incomplete,
no_match,
remaining,
multiple,
relationship,
nan_distinct,
chr_proxy_collate,
needles_arg,
haystack_arg,
frame
)
}
# ------------------------------------------------------------------------------
#' Internal FAQ - Implementation of `vec_locate_matches()`
#'
#' ```{r, child = "man/faq/internal/matches-algorithm.Rmd"}
#' ```
#'
#' @name internal-faq-matches-algorithm
NULL
# ------------------------------------------------------------------------------
# Helper used for testing and in the internal FAQ.
# It needs to live in R/ to be usable by the FAQ Rmd.
compute_nesting_container_info <- function(x, condition) {
.Call(ffi_compute_nesting_container_info, x, condition)
}
# ------------------------------------------------------------------------------
stop_matches <- function(message = NULL, class = NULL, ..., call = caller_env()) {
stop_vctrs(
message = message,
class = c(class, "vctrs_error_matches"),
...,
call = call
)
}
warn_matches <- function(message, class = NULL, ..., call = caller_env()) {
warn_vctrs(
message = message,
class = c(class, "vctrs_warning_matches"),
...,
call = call
)
}
# ------------------------------------------------------------------------------
stop_matches_overflow <- function(size, call) {
size <- format(size, scientific = FALSE)
# Pre-generating the message in this case because we want to use
# `.internal = TRUE` and that doesn't work with lazy messages
message <- c(
"Match procedure results in an allocation larger than 2^31-1 elements.",
i = glue::glue("Attempted allocation size was {size}.")
)
stop_matches(
message = message,
class = "vctrs_error_matches_overflow",
size = size,
call = call,
.internal = TRUE
)
}
# ------------------------------------------------------------------------------
stop_matches_nothing <- function(i, needles_arg, haystack_arg, call) {
stop_matches(
class = "vctrs_error_matches_nothing",
i = i,
needles_arg = needles_arg,
haystack_arg = haystack_arg,
call = call
)
}
#' @export
cnd_header.vctrs_error_matches_nothing <- function(cnd, ...) {
glue::glue("Each value of `{cnd$needles_arg}` must have a match in `{cnd$haystack_arg}`.")
}
#' @export
cnd_body.vctrs_error_matches_nothing <- function(cnd, ...) {
bullet <- glue::glue("Location {cnd$i} of `{cnd$needles_arg}` does not have a match.")
bullet <- c(x = bullet)
format_error_bullets(bullet)
}
# ------------------------------------------------------------------------------
stop_matches_remaining <- function(i, needles_arg, haystack_arg, call) {
stop_matches(
class = "vctrs_error_matches_remaining",
i = i,
needles_arg = needles_arg,
haystack_arg = haystack_arg,
call = call
)
}
#' @export
cnd_header.vctrs_error_matches_remaining <- function(cnd, ...) {
glue::glue("Each value of `{cnd$haystack_arg}` must be matched by `{cnd$needles_arg}`.")
}
#' @export
cnd_body.vctrs_error_matches_remaining <- function(cnd, ...) {
bullet <- glue::glue("Location {cnd$i} of `{cnd$haystack_arg}` was not matched.")
bullet <- c(x = bullet)
format_error_bullets(bullet)
}
# ------------------------------------------------------------------------------
stop_matches_incomplete <- function(i, needles_arg, call) {
stop_matches(
class = "vctrs_error_matches_incomplete",
i = i,
needles_arg = needles_arg,
call = call
)
}
#' @export
cnd_header.vctrs_error_matches_incomplete <- function(cnd, ...) {
glue::glue("`{cnd$needles_arg}` can't contain missing values.")
}
#' @export
cnd_body.vctrs_error_matches_incomplete <- function(cnd, ...) {
bullet <- glue::glue("Location {cnd$i} contains missing values.")
bullet <- c(x = bullet)
format_error_bullets(bullet)
}
# ------------------------------------------------------------------------------
stop_matches_multiple <- function(i, needles_arg, haystack_arg, call) {
stop_matches(
class = "vctrs_error_matches_multiple",
i = i,
needles_arg = needles_arg,
haystack_arg = haystack_arg,
call = call
)
}
#' @export
cnd_header.vctrs_error_matches_multiple <- function(cnd, ...) {
cnd_matches_multiple_header(cnd$needles_arg, cnd$haystack_arg)
}
#' @export
cnd_body.vctrs_error_matches_multiple <- function(cnd, ...) {
cnd_matches_multiple_body(cnd$i, cnd$needles_arg)
}
# ------------------------------------------------------------------------------
warn_matches_multiple <- function(i, needles_arg, haystack_arg, call) {
message <- paste(
cnd_matches_multiple_header(needles_arg, haystack_arg),
cnd_matches_multiple_body(i, needles_arg),
sep = "\n"
)
warn_matches(
message = message,
class = "vctrs_warning_matches_multiple",
i = i,
needles_arg = needles_arg,
haystack_arg = haystack_arg,
call = call
)
}
# ------------------------------------------------------------------------------
stop_matches_relationship_one_to_one <- function(i, which, needles_arg, haystack_arg, call) {
stop_matches_relationship(
class = "vctrs_error_matches_relationship_one_to_one",
i = i,
which = which,
needles_arg = needles_arg,
haystack_arg = haystack_arg,
call = call
)
}
#' @export
cnd_header.vctrs_error_matches_relationship_one_to_one <- function(cnd, ...) {
if (cnd$which == "needles") {
cnd_matches_multiple_header(cnd$needles_arg, cnd$haystack_arg)
} else {
cnd_matches_multiple_header(cnd$haystack_arg, cnd$needles_arg)
}
}
#' @export
cnd_body.vctrs_error_matches_relationship_one_to_one <- function(cnd, ...) {
if (cnd$which == "needles") {
cnd_matches_multiple_body(cnd$i, cnd$needles_arg)
} else {
cnd_matches_multiple_body(cnd$i, cnd$haystack_arg)
}
}
stop_matches_relationship_one_to_many <- function(i, needles_arg, haystack_arg, call) {
stop_matches_relationship(
class = "vctrs_error_matches_relationship_one_to_many",
i = i,
needles_arg = needles_arg,
haystack_arg = haystack_arg,
call = call
)
}
#' @export
cnd_header.vctrs_error_matches_relationship_one_to_many <- function(cnd, ...) {
cnd_matches_multiple_header(cnd$haystack_arg, cnd$needles_arg)
}
#' @export
cnd_body.vctrs_error_matches_relationship_one_to_many <- function(cnd, ...) {
cnd_matches_multiple_body(cnd$i, cnd$haystack_arg)
}
stop_matches_relationship_many_to_one <- function(i, needles_arg, haystack_arg, call) {
stop_matches_relationship(
class = "vctrs_error_matches_relationship_many_to_one",
i = i,
needles_arg = needles_arg,
haystack_arg = haystack_arg,
call = call
)
}
#' @export
cnd_header.vctrs_error_matches_relationship_many_to_one <- function(cnd, ...) {
cnd_matches_multiple_header(cnd$needles_arg, cnd$haystack_arg)
}
#' @export
cnd_body.vctrs_error_matches_relationship_many_to_one <- function(cnd, ...) {
cnd_matches_multiple_body(cnd$i, cnd$needles_arg)
}
stop_matches_relationship <- function(class = NULL, ..., call = caller_env()) {
stop_matches(
class = c(class, "vctrs_error_matches_relationship"),
...,
call = call
)
}
cnd_matches_multiple_header <- function(x_arg, y_arg) {
glue::glue("Each value of `{x_arg}` can match at most 1 value from `{y_arg}`.")
}
cnd_matches_multiple_body <- function(i, name) {
bullet <- glue::glue("Location {i} of `{name}` matches multiple values.")
bullet <- c(x = bullet)
format_error_bullets(bullet)
}
# ------------------------------------------------------------------------------
warn_matches_relationship_many_to_many <- function(i, j, needles_arg, haystack_arg, call) {
message <- paste(
glue::glue("Detected an unexpected many-to-many relationship between `{needles_arg}` and `{haystack_arg}`."),
cnd_matches_multiple_body(i, needles_arg),
cnd_matches_multiple_body(j, haystack_arg),
sep = "\n"
)
warn_matches_relationship(
message = message,
class = "vctrs_warning_matches_relationship_many_to_many",
i = i,
j = j,
needles_arg = needles_arg,
haystack_arg = haystack_arg,
call = call
)
}
warn_matches_relationship <- function(message, class = NULL, ..., call = caller_env()) {
warn_matches(
message = message,
class = c(class, "vctrs_warning_matches_relationship"),
...,
call = call
)
}
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/match.R
|
#' Missing values
#'
#' @description
#' - `vec_detect_missing()` returns a logical vector the same size as `x`. For
#' each element of `x`, it returns `TRUE` if the element is missing, and `FALSE`
#' otherwise.
#'
#' - `vec_any_missing()` returns a single `TRUE` or `FALSE` depending on whether
#' or not `x` has _any_ missing values.
#'
#' ## Differences with [is.na()]
#'
#' Data frame rows are only considered missing if every element in the row is
#' missing. Similarly, [record vector][new_rcrd()] elements are only considered
#' missing if every field in the record is missing. Put another way, rows with
#' _any_ missing values are considered [incomplete][vec_detect_complete()], but
#' only rows with _all_ missing values are considered missing.
#'
#' List elements are only considered missing if they are `NULL`.
#'
#' @param x A vector
#'
#' @return
#' - `vec_detect_missing()` returns a logical vector the same size as `x`.
#'
#' - `vec_any_missing()` returns a single `TRUE` or `FALSE`.
#'
#' @section Dependencies:
#' - [vec_proxy_equal()]
#'
#' @name missing
#' @seealso [vec_detect_complete()]
#'
#' @examples
#' x <- c(1, 2, NA, 4, NA)
#'
#' vec_detect_missing(x)
#' vec_any_missing(x)
#'
#' # Data frames are iterated over rowwise, and only report a row as missing
#' # if every element of that row is missing. If a row is only partially
#' # missing, it is said to be incomplete, but not missing.
#' y <- c("a", "b", NA, "d", "e")
#' df <- data_frame(x = x, y = y)
#'
#' df$missing <- vec_detect_missing(df)
#' df$incomplete <- !vec_detect_complete(df)
#' df
NULL
#' @rdname missing
#' @export
vec_detect_missing <- function(x) {
.Call(ffi_vec_detect_missing, x)
}
#' @rdname missing
#' @export
vec_any_missing <- function(x) {
.Call(ffi_vec_any_missing, x)
}
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/missing.R
|
#' Retrieve and repair names
#'
#' @description
#'
#' `vec_as_names()` takes a character vector of names and repairs it
#' according to the `repair` argument. It is the r-lib and tidyverse
#' equivalent of [base::make.names()].
#'
#' vctrs deals with a few levels of name repair:
#'
#' * `minimal` names exist. The `names` attribute is not `NULL`. The
#' name of an unnamed element is `""` and never `NA`. For instance,
#' `vec_as_names()` always returns minimal names and data frames
#' created by the tibble package have names that are, at least,
#' `minimal`.
#'
#' * `unique` names are `minimal`, have no duplicates, and can be used
#' where a variable name is expected. Empty names, `...`, and
#' `..` followed by a sequence of digits are banned.
#'
#' - All columns can be accessed by name via `df[["name"]]` and
#' ``df$`name` `` and ``with(df, `name`)``.
#'
#' * `universal` names are `unique` and syntactic (see Details for
#' more).
#'
#' - Names work everywhere, without quoting: `df$name` and `with(df,
#' name)` and `lm(name1 ~ name2, data = df)` and
#' `dplyr::select(df, name)` all work.
#'
#' `universal` implies `unique`, `unique` implies `minimal`. These
#' levels are nested.
#'
#'
#' @inheritParams rlang::args_error_context
#' @inheritParams rlang::args_dots_empty
#'
#' @param names A character vector.
#' @param repair Either a string or a function. If a string, it must be one of
#' `"check_unique"`, `"minimal"`, `"unique"`, `"universal"`, `"unique_quiet"`,
#' or `"universal_quiet"`. If a function, it is invoked with a vector of
#' minimal names and must return minimal names, otherwise an error is thrown.
#'
#' * Minimal names are never `NULL` or `NA`. When an element doesn't
#' have a name, its minimal name is an empty string.
#'
#' * Unique names are unique. A suffix is appended to duplicate
#' names to make them unique.
#'
#' * Universal names are unique and syntactic, meaning that you can
#' safely use the names as variables without causing a syntax
#' error.
#'
#' The `"check_unique"` option doesn't perform any name repair.
#' Instead, an error is raised if the names don't suit the
#' `"unique"` criteria.
#'
#' The options `"unique_quiet"` and `"universal_quiet"` are here to help the
#' user who calls this function indirectly, via another function which exposes
#' `repair` but not `quiet`. Specifying `repair = "unique_quiet"` is like
#' specifying `repair = "unique", quiet = TRUE`. When the `"*_quiet"` options
#' are used, any setting of `quiet` is silently overridden.
#' @param repair_arg If specified and `repair = "check_unique"`, any errors
#' will include a hint to set the `repair_arg`.
#' @param quiet By default, the user is informed of any renaming
#' caused by repairing the names. This only concerns unique and
#' universal repairing. Set `quiet` to `TRUE` to silence the
#' messages.
#'
#' Users can silence the name repair messages by setting the
#' `"rlib_name_repair_verbosity"` global option to `"quiet"`.
#'
#' @section `minimal` names:
#'
#' `minimal` names exist. The `names` attribute is not `NULL`. The
#' name of an unnamed element is `""` and never `NA`.
#'
#' Examples:
#'
#' ```
#' Original names of a vector with length 3: NULL
#' minimal names: "" "" ""
#'
#' Original names: "x" NA
#' minimal names: "x" ""
#' ```
#'
#'
#' @section `unique` names:
#'
#' `unique` names are `minimal`, have no duplicates, and can be used
#' (possibly with backticks) in contexts where a variable is
#' expected. Empty names, `...`, and `..` followed by a sequence of
#' digits are banned. If a data frame has `unique` names, you can
#' index it by name, and also access the columns by name. In
#' particular, `df[["name"]]` and `` df$`name` `` and also ``with(df,
#' `name`)`` always work.
#'
#' There are many ways to make names `unique`. We append a suffix of the form
#' `...j` to any name that is `""` or a duplicate, where `j` is the position.
#' We also change `..#` and `...` to `...#`.
#'
#' Example:
#'
#' ```
#' Original names: "" "x" "" "y" "x" "..2" "..."
#' unique names: "...1" "x...2" "...3" "y" "x...5" "...6" "...7"
#' ```
#'
#' Pre-existing suffixes of the form `...j` are always stripped, prior
#' to making names `unique`, i.e. reconstructing the suffixes. If this
#' interacts poorly with your names, you should take control of name
#' repair.
#'
#'
#' @section `universal` names:
#'
#' `universal` names are `unique` and syntactic, meaning they:
#'
#' * Are never empty (inherited from `unique`).
#' * Have no duplicates (inherited from `unique`).
#' * Are not `...`. Do not have the form `..i`, where `i` is a
#' number (inherited from `unique`).
#' * Consist of letters, numbers, and the dot `.` or underscore `_`
#' characters.
#' * Start with a letter or start with the dot `.` not followed by a
#' number.
#' * Are not a [reserved] word, e.g., `if` or `function` or `TRUE`.
#'
#' If a vector has `universal` names, variable names can be used
#' "as is" in code. They work well with nonstandard evaluation, e.g.,
#' `df$name` works.
#'
#' vctrs has a different method of making names syntactic than
#' [base::make.names()]. In general, vctrs prepends one or more dots
#' `.` until the name is syntactic.
#'
#' Examples:
#'
#' ```
#' Original names: "" "x" NA "x"
#' universal names: "...1" "x...2" "...3" "x...4"
#'
#' Original names: "(y)" "_z" ".2fa" "FALSE"
#' universal names: ".y." "._z" "..2fa" ".FALSE"
#' ```
#'
#' @seealso [rlang::names2()] returns the names of an object, after
#' making them `minimal`.
#' @examples
#' # By default, `vec_as_names()` returns minimal names:
#' vec_as_names(c(NA, NA, "foo"))
#'
#' # You can make them unique:
#' vec_as_names(c(NA, NA, "foo"), repair = "unique")
#'
#' # Universal repairing fixes any non-syntactic name:
#' vec_as_names(c("_foo", "+"), repair = "universal")
#' @export
vec_as_names <- function(names,
...,
repair = c("minimal", "unique", "universal", "check_unique", "unique_quiet", "universal_quiet"),
repair_arg = NULL,
quiet = FALSE,
call = caller_env()) {
check_dots_empty0(...)
.Call(
ffi_vec_as_names,
names,
repair,
quiet,
environment()
)
}
# TODO! Error calls
validate_name_repair_arg <- function(repair) {
.Call(vctrs_validate_name_repair_arg, repair)
}
validate_minimal_names <- function(names, n = NULL) {
.Call(vctrs_validate_minimal_names, names, n)
}
validate_unique <- function(names,
arg = "",
n = NULL,
call = caller_env()) {
validate_minimal_names(names, n)
empty_names <- detect_empty_names(names)
if (has_length(empty_names)) {
stop_names_cannot_be_empty(names, call = call)
}
dot_dot_name <- detect_dot_dot(names)
if (has_length(dot_dot_name)) {
stop_names_cannot_be_dot_dot(names, call = call)
}
if (anyDuplicated(names)) {
stop_names_must_be_unique(names, arg, call = call)
}
invisible(names)
}
detect_empty_names <- function(names) {
which(names == "")
}
detect_dot_dot <- function(names) {
grep("^[.][.](?:[.]|[1-9][0-9]*)$", names)
}
#' Get or set the names of a vector
#'
#' @description
#' These functions work like [rlang::names2()], [names()] and [names<-()],
#' except that they return or modify the the rowwise names of the vector. These are:
#' * The usual `names()` for atomic vectors and lists
#' * The row names for data frames and matrices
#' * The names of the first dimension for arrays
#' Rowwise names are size consistent: the length of the names always equals
#' [vec_size()].
#'
#' `vec_names2()` returns the repaired names from a vector, even if it is unnamed.
#' See [vec_as_names()] for details on name repair.
#'
#' `vec_names()` is a bare-bones version that returns `NULL` if the vector is
#' unnamed.
#'
#' `vec_set_names()` sets the names or removes them.
#'
#' @param x A vector with names
#' @param names A character vector, or `NULL`.
#' @inheritParams vec_as_names
#'
#' @return
#' `vec_names2()` returns the names of `x`, repaired.
#' `vec_names()` returns the names of `x` or `NULL` if unnamed.
#' `vec_set_names()` returns `x` with names updated.
#'
#' @name vec_names
#' @export
#' @examples
#' vec_names2(1:3)
#' vec_names2(1:3, repair = "unique")
#' vec_names2(c(a = 1, b = 2))
#'
#' # `vec_names()` consistently returns the rowwise names of data frames and arrays:
#' vec_names(data.frame(a = 1, b = 2))
#' names(data.frame(a = 1, b = 2))
#' vec_names(mtcars)
#' names(mtcars)
#' vec_names(Titanic)
#' names(Titanic)
#'
#' vec_set_names(1:3, letters[1:3])
#' vec_set_names(data.frame(a = 1:3), letters[1:3])
vec_names2 <- function(x,
...,
repair = c("minimal", "unique", "universal", "check_unique", "unique_quiet", "universal_quiet"),
quiet = FALSE) {
check_dots_empty0(...)
repair <- validate_name_repair_arg(repair)
if (is_function(repair)) {
names <- minimal_names(x)
new_names <- validate_minimal_names(repair(names), n = length(names))
if (!quiet) {
describe_repair(names, new_names)
}
return(new_names)
}
switch(
repair,
minimal = minimal_names(x),
unique = unique_names(x, quiet = quiet),
universal = as_universal_names(minimal_names(x), quiet = quiet),
check_unique = validate_unique(minimal_names(x)),
unique_quiet = unique_names(x, quiet = TRUE),
universal_quiet = as_universal_names(minimal_names(x), quiet = TRUE)
)
}
vec_repair_names <- function(x,
repair = c("minimal", "unique", "universal", "check_unique", "unique_quiet", "universal_quiet"),
...,
quiet = FALSE) {
if (is.data.frame(x)) {
x
} else {
vec_set_names(x, vec_names2(x, ..., repair = repair, quiet = quiet))
}
}
minimal_names <- function(x) {
.Call(ffi_minimal_names, x)
}
unique_names <- function(x, quiet = FALSE) {
.Call(ffi_unique_names, x, quiet)
}
#' @rdname vec_names
#' @export
vec_names <- function(x) {
.Call(vctrs_names, x)
}
as_minimal_names <- function(names) {
.Call(ffi_as_minimal_names, names)
}
as_unique_names <- function(names, quiet = FALSE) {
.Call(vctrs_as_unique_names, names, quiet)
}
as_universal_names <- function(names, quiet = FALSE) {
new_names <- names
new_names[] <- ""
naked_names <- strip_pos(two_to_three_dots(names))
empty <- naked_names %in% c("", "...")
new_names[!empty] <- make_syntactic(naked_names[!empty])
needs_suffix <- empty | vec_duplicate_detect(new_names)
new_names <- append_pos(new_names, needs_suffix = needs_suffix)
if (!quiet) {
describe_repair(names, new_names)
}
new_names
}
two_to_three_dots <- function(names) {
sub("(^[.][.][1-9][0-9]*$)", ".\\1", names)
}
append_pos <- function(names, needs_suffix) {
need_append_pos <- which(needs_suffix)
names[need_append_pos] <- paste0(names[need_append_pos], "...", need_append_pos)
names
}
strip_pos <- function(names) {
rx <- "([.][.][.][1-9][0-9]*)+$"
gsub(rx, "", names) %|% ""
}
# Makes each individual name syntactic but does not enforce unique-ness
make_syntactic <- function(names) {
names[is.na(names)] <- ""
names[names == ""] <- "."
names[names == "..."] <- "...."
names <- sub("^_", "._", names)
new_names <- make.names(names)
X_prefix <- grepl("^X", new_names) & !grepl("^X", names)
new_names[X_prefix] <- sub("^X", "", new_names[X_prefix])
dot_suffix <- which(new_names == paste0(names, "."))
new_names[dot_suffix] <- sub("^(.*)[.]$", ".\\1", new_names[dot_suffix])
# Illegal characters have been replaced with '.' via make.names()
# however, we have:
# * Declined its addition of 'X' prefixes.
# * Turned its '.' suffixes to '.' prefixes.
regex <- paste0(
"^(?<leading_dots>[.]{0,2})",
"(?<numbers>[0-9]*)",
"(?<leftovers>[^0-9]?.*$)"
)
re <- re_match(new_names, pattern = regex)
needs_dots <- which(re$numbers != "")
needs_third_dot <- (re$leftovers[needs_dots] == "")
re$leading_dots[needs_dots] <- ifelse(needs_third_dot, "...", "..")
new_names <- paste0(re$leading_dots, re$numbers, re$leftovers)
new_names
}
# From rematch2, except we don't add tbl_df or tbl classes to the return value
re_match <- function(text, pattern, perl = TRUE, ...) {
stopifnot(
is.character(pattern),
length(pattern) == 1,
!is.na(pattern)
)
text <- as.character(text)
match <- regexpr(pattern, text, perl = perl, ...)
start <- as.vector(match)
length <- attr(match, "match.length")
end <- start + length - 1L
matchstr <- substring(text, start, end)
matchstr[ start == -1 ] <- NA_character_
res <- data.frame(
stringsAsFactors = FALSE,
.text = text,
.match = matchstr
)
if (!is.null(attr(match, "capture.start"))) {
gstart <- attr(match, "capture.start")
glength <- attr(match, "capture.length")
gend <- gstart + glength - 1L
groupstr <- substring(text, gstart, gend)
groupstr[ gstart == -1 ] <- NA_character_
dim(groupstr) <- dim(gstart)
res <- cbind(groupstr, res, stringsAsFactors = FALSE)
}
names(res) <- c(attr(match, "capture.names"), ".text", ".match")
res
}
describe_repair <- function(orig_names, names) {
names_inform_repair(orig_names, names)
}
bullets <- function(..., header = NULL) {
problems <- c(...)
MAX_BULLETS <- 6L
if (length(problems) >= MAX_BULLETS) {
n_more <- length(problems) - MAX_BULLETS + 1L
problems[[MAX_BULLETS]] <- "..."
length(problems) <- MAX_BULLETS
}
info <- paste0("* ", problems, collapse = "\n")
if (!is.null(header)) {
info <- paste0(header, "\n", info)
}
info
}
# Used in names.c
set_rownames_dispatch <- function(x, names) {
rownames(x) <- names
x
}
# Used in names.c
set_names_dispatch <- function(x, names) {
names(x) <- names
x
}
#' @rdname vec_names
#' @export
vec_set_names <- function(x, names) {
.Call(vctrs_set_names, x, names)
}
#' Repair names with legacy method
#'
#' This standardises names with the legacy approach that was used in
#' tidyverse packages (such as tibble, tidyr, and readxl) before
#' [vec_as_names()] was implemented. This tool is meant to help
#' transitioning to the new name repairing standard and will be
#' deprecated and removed from the package some time in the future.
#'
#' @inheritParams vec_as_names
#' @param prefix,sep Prefix and separator for repaired names.
#'
#' @examples
#' if (rlang::is_installed("tibble")) {
#'
#' library(tibble)
#'
#' # Names repair is turned off by default in tibble:
#' try(tibble(a = 1, a = 2))
#'
#' # You can turn it on by supplying a repair method:
#' tibble(a = 1, a = 2, .name_repair = "universal")
#'
#' # If you prefer the legacy method, use `vec_as_names_legacy()`:
#' tibble(a = 1, a = 2, .name_repair = vec_as_names_legacy)
#'
#' }
#' @keywords internal
#' @export
vec_as_names_legacy <- function(names, prefix = "V", sep = "") {
if (length(names) == 0) {
return(character())
}
blank <- names == ""
names[!blank] <- make.unique(names[!blank], sep = sep)
new_nms <- setdiff(paste(prefix, seq_along(names), sep = sep), names)
names[blank] <- new_nms[seq_len(sum(blank))]
names
}
#' Name specifications
#'
#' @description
#'
#' A name specification describes how to combine an inner and outer
#' names. This sort of name combination arises when concatenating
#' vectors or flattening lists. There are two possible cases:
#'
#' * Named vector:
#'
#' ```
#' vec_c(outer = c(inner1 = 1, inner2 = 2))
#' ```
#'
#' * Unnamed vector:
#'
#' ```
#' vec_c(outer = 1:2)
#' ```
#'
#' In r-lib and tidyverse packages, these cases are errors by default,
#' because there's no behaviour that works well for every case.
#' Instead, you can provide a name specification that describes how to
#' combine the inner and outer names of inputs. Name specifications
#' can refer to:
#'
#' * `outer`: The external name recycled to the size of the input
#' vector.
#'
#' * `inner`: Either the names of the input vector, or a sequence of
#' integer from 1 to the size of the vector if it is unnamed.
#'
#' @param name_spec,.name_spec A name specification for combining
#' inner and outer names. This is relevant for inputs passed with a
#' name, when these inputs are themselves named, like `outer =
#' c(inner = 1)`, or when they have length greater than 1: `outer =
#' 1:2`. By default, these cases trigger an error. You can resolve
#' the error by providing a specification that describes how to
#' combine the names or the indices of the inner vector with the
#' name of the input. This specification can be:
#'
#' * A function of two arguments. The outer name is passed as a
#' string to the first argument, and the inner names or positions
#' are passed as second argument.
#'
#' * An anonymous function as a purrr-style formula.
#'
#' * A glue specification of the form `"{outer}_{inner}"`.
#'
#' * An [rlang::zap()] object, in which case both outer and inner
#' names are ignored and the result is unnamed.
#'
#' See the [name specification topic][name_spec].
#'
#' @examples
#' # By default, named inputs must be length 1:
#' vec_c(name = 1) # ok
#' try(vec_c(name = 1:3)) # bad
#'
#' # They also can't have internal names, even if scalar:
#' try(vec_c(name = c(internal = 1))) # bad
#'
#' # Pass a name specification to work around this. A specification
#' # can be a glue string referring to `outer` and `inner`:
#' vec_c(name = 1:3, other = 4:5, .name_spec = "{outer}")
#' vec_c(name = 1:3, other = 4:5, .name_spec = "{outer}_{inner}")
#'
#' # They can also be functions:
#' my_spec <- function(outer, inner) paste(outer, inner, sep = "_")
#' vec_c(name = 1:3, other = 4:5, .name_spec = my_spec)
#'
#' # Or purrr-style formulas for anonymous functions:
#' vec_c(name = 1:3, other = 4:5, .name_spec = ~ paste0(.x, .y))
#' @name name_spec
NULL
apply_name_spec <- function(name_spec, outer, inner, n = length(inner)) {
.Call(ffi_apply_name_spec, name_spec, outer, inner, n)
}
glue_as_name_spec <- function(`_spec`) {
function(inner, outer) {
glue::glue(`_spec`)
}
}
# Evaluate glue specs in a child of base for now
environment(glue_as_name_spec) <- baseenv()
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/names.R
|
#' Mathematical operations
#'
#' This generic provides a common dispatch mechanism for all regular unary
#' mathematical functions. It is used as a common wrapper around many of the
#' Summary group generics, the Math group generics, and a handful of other
#' mathematical functions like `mean()` (but not `var()` or `sd()`).
#'
#' `vec_math_base()` is provided as a convenience for writing methods. It
#' calls the base `.fn` on the underlying [vec_data()].
#'
#' @section Included functions:
#'
#' * From the [Summary] group generic:
#' `prod()`, `sum()`, `any()`, `all()`.
#'
#' * From the [Math] group generic:
#' `abs()`, `sign()`, `sqrt()`, `ceiling()`, `floor()`, `trunc()`, `cummax()`,
#' `cummin()`, `cumprod()`, `cumsum()`, `log()`, `log10()`, `log2()`,
#' `log1p()`, `acos()`, `acosh()`, `asin()`, `asinh()`, `atan()`, `atanh()`,
#' `exp()`, `expm1()`, `cos()`, `cosh()`, `cospi()`, `sin()`, `sinh()`,
#' `sinpi()`, `tan()`, `tanh()`, `tanpi()`, `gamma()`, `lgamma()`,
#' `digamma()`, `trigamma()`.
#'
#' * Additional generics: `mean()`, `is.nan()`, `is.finite()`, `is.infinite()`.
#'
#' Note that `median()` is currently not implemented, and `sd()` and
#' `var()` are currently not generic and so do not support custom
#' classes.
#'
#' @seealso [vec_arith()] for the equivalent for the arithmetic infix operators.
#' @param .fn A mathematical function from the base package, as a string.
#' @param .x A vector.
#' @param ... Additional arguments passed to `.fn`.
#' @keywords internal
#' @export
#' @examples
#' x <- new_vctr(c(1, 2.5, 10))
#' x
#'
#' abs(x)
#' sum(x)
#' cumsum(x)
vec_math <- function(.fn, .x, ...) {
UseMethod("vec_math", .x)
}
#' @export
vec_math.default <- function(.fn, .x, ...) {
if (!is_double(.x) && !is_logical_dispatch(.fn, .x)) {
stop_unimplemented(.x, "vec_math")
}
out <- vec_math_base(.fn, .x, ...)
# Don't restore output of logical predicates like `any()`,
# `is.finite()`, or `is.nan()`
if (is_double(out)) {
out <- vec_restore(out, .x)
}
out
}
is_logical_dispatch <- function(fn, x) {
is_logical(x) && fn %in% c("any", "all")
}
#' @export
#' @rdname vec_math
vec_math_base <- function(.fn, .x, ...) {
.fn <- getExportedValue("base", .fn)
.fn(vec_data(.x), ...)
}
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/numeric.R
|
# TODO: Use this NEWS bullet when we move to the new `vec_order()` algorithm
#
# * `vec_order()` and `vec_sort()` now use a custom radix sort algorithm, rather
# than relying on `order()`. The implementation is based on data.table’s
# `forder()` and their earlier contribution to R’s `order()`. There are four
# major changes, outlined below, the first two of which are breaking changes.
# If you need to retain the old ordering behavior, use `vec_order_base()`.
#
# * Character vectors now order in the C locale by default, which is _much_
# faster than ordering in the system's locale. To order in a specific locale,
# you can provide a character proxy function through `chr_proxy_collate`,
# such as `stringi::stri_sort_key()`.
#
# * Optional arguments, such as `direction` and `na_value`, must now be
# specified by name. Specifying by position will result in an error.
#
# * When ordering data frames, you can now control the behavior of `direction`
# and `na_value` on a per column basis.
#
# * There is a new `nan_distinct` argument for differentiating between `NaN`
# and `NA` in double and complex vectors.
#' Order and sort vectors
#'
#' @description
#' `vec_order_radix()` computes the order of `x`. For data frames, the order is
#' computed along the rows by computing the order of the first column and
#' using subsequent columns to break ties.
#'
#' `vec_sort_radix()` sorts `x`. It is equivalent to `vec_slice(x, vec_order_radix(x))`.
#'
#' @inheritParams rlang::args_dots_empty
#'
#' @param x A vector
#' @param direction Direction to sort in.
#' - A single `"asc"` or `"desc"` for ascending or descending order
#' respectively.
#' - For data frames, a length `1` or `ncol(x)` character vector containing
#' only `"asc"` or `"desc"`, specifying the direction for each column.
#' @param na_value Ordering of missing values.
#' - A single `"largest"` or `"smallest"` for ordering missing values as the
#' largest or smallest values respectively.
#' - For data frames, a length `1` or `ncol(x)` character vector containing
#' only `"largest"` or `"smallest"`, specifying how missing values should
#' be ordered within each column.
#' @param nan_distinct A single logical specifying whether or not `NaN` should
#' be considered distinct from `NA` for double and complex vectors. If `TRUE`,
#' `NaN` will always be ordered between `NA` and non-missing numbers.
#' @param chr_proxy_collate A function generating an alternate representation
#' of character vectors to use for collation, often used for locale-aware
#' ordering.
#' - If `NULL`, no transformation is done.
#' - Otherwise, this must be a function of one argument. If the input contains
#' a character vector, it will be passed to this function after it has been
#' translated to UTF-8. This function should return a character vector with
#' the same length as the input. The result should sort as expected in the
#' C-locale, regardless of encoding.
#'
#' For data frames, `chr_proxy_collate` will be applied to all character
#' columns.
#'
#' Common transformation functions include: `tolower()` for case-insensitive
#' ordering and `stringi::stri_sort_key()` for locale-aware ordering.
#'
#' @return
#' * `vec_order_radix()` an integer vector the same size as `x`.
#' * `vec_sort_radix()` a vector with the same size and type as `x`.
#'
#' @section Differences with `order()`:
#'
#' Unlike the `na.last` argument of `order()` which decides the positions of
#' missing values irrespective of the `decreasing` argument, the `na_value`
#' argument of `vec_order_radix()` interacts with `direction`. If missing values
#' are considered the largest value, they will appear last in ascending order,
#' and first in descending order.
#'
#' Character vectors are ordered in the C-locale. This is different from
#' `base::order()`, which respects `base::Sys.setlocale()`. Sorting in a
#' consistent locale can produce more reproducible results between different
#' sessions and platforms, however, the results of sorting in the C-locale
#' can be surprising. For example, capital letters sort before lower case
#' letters. Sorting `c("b", "C", "a")` with `vec_sort_radix()` will return
#' `c("C", "a", "b")`, but with `base::order()` will return `c("a", "b", "C")`
#' unless `base::order(method = "radix")` is explicitly set, which also uses
#' the C-locale. While sorting with the C-locale can be useful for
#' algorithmic efficiency, in many real world uses it can be the cause of
#' data analysis mistakes. To balance these trade-offs, you can supply a
#' `chr_proxy_collate` function to transform character vectors into an
#' alternative representation that orders in the C-locale in a less surprising
#' way. For example, providing [base::tolower()] as a transform will order the
#' original vector in a case-insensitive manner. Locale-aware ordering can be
#' achieved by providing `stringi::stri_sort_key()` as a transform, setting the
#' collation options as appropriate for your locale.
#'
#' Character vectors are always translated to UTF-8 before ordering, and before
#' any transform is applied by `chr_proxy_collate`.
#'
#' For complex vectors, if either the real or imaginary component is `NA` or
#' `NaN`, then the entire observation is considered missing.
#'
#' @section Dependencies of `vec_order_radix()`:
#' * [vec_proxy_order()]
#'
#' @section Dependencies of `vec_sort_radix()`:
#' * [vec_order_radix()]
#' * [vec_slice()]
#'
#' @name order-radix
#' @keywords internal
#'
#' @examples
#' if (FALSE) {
#'
#' x <- round(sample(runif(5), 9, replace = TRUE), 3)
#' x <- c(x, NA)
#'
#' vec_order_radix(x)
#' vec_sort_radix(x)
#' vec_sort_radix(x, direction = "desc")
#'
#' # Can also handle data frames
#' df <- data.frame(g = sample(2, 10, replace = TRUE), x = x)
#' vec_order_radix(df)
#' vec_sort_radix(df)
#' vec_sort_radix(df, direction = "desc")
#'
#' # For data frames, `direction` and `na_value` are allowed to be vectors
#' # with length equal to the number of columns in the data frame
#' vec_sort_radix(
#' df,
#' direction = c("desc", "asc"),
#' na_value = c("largest", "smallest")
#' )
#'
#' # Character vectors are ordered in the C locale, which orders capital letters
#' # below lowercase ones
#' y <- c("B", "A", "a")
#' vec_sort_radix(y)
#'
#' # To order in a case-insensitive manner, provide a `chr_proxy_collate`
#' # function that transforms the strings to all lowercase
#' vec_sort_radix(y, chr_proxy_collate = tolower)
#'
#' }
NULL
#' @rdname order-radix
vec_order_radix <- function(x,
...,
direction = "asc",
na_value = "largest",
nan_distinct = FALSE,
chr_proxy_collate = NULL) {
check_dots_empty0(...)
.Call(vctrs_order, x, direction, na_value, nan_distinct, chr_proxy_collate)
}
#' @rdname order-radix
vec_sort_radix <- function(x,
...,
direction = "asc",
na_value = "largest",
nan_distinct = FALSE,
chr_proxy_collate = NULL) {
check_dots_empty0(...)
idx <- vec_order_radix(
x = x,
direction = direction,
na_value = na_value,
nan_distinct = nan_distinct,
chr_proxy_collate = chr_proxy_collate
)
vec_slice(x, idx)
}
# ------------------------------------------------------------------------------
#' Locate sorted groups
#'
#' @description
#' `r lifecycle::badge("experimental")`
#'
#' `vec_locate_sorted_groups()` returns a data frame containing a `key` column
#' with sorted unique groups, and a `loc` column with the locations of each
#' group in `x`. It is similar to [vec_group_loc()], except the groups are
#' returned sorted rather than by first appearance.
#'
#' @details
#' `vec_locate_sorted_groups(x)` is equivalent to, but faster than:
#'
#' ```
#' info <- vec_group_loc(x)
#' vec_slice(info, vec_order(info$key))
#' ```
#'
#' @inheritParams order-radix
#'
#' @return
#' A two column data frame with size equal to `vec_size(vec_unique(x))`.
#' * A `key` column of type `vec_ptype(x)`.
#' * A `loc` column of type list, with elements of type integer.
#'
#' @section Dependencies of `vec_locate_sorted_groups()`:
#' * [vec_proxy_order()]
#'
#' @export
#' @keywords internal
#' @examples
#' df <- data.frame(
#' g = sample(2, 10, replace = TRUE),
#' x = c(NA, sample(5, 9, replace = TRUE))
#' )
#'
#' # `vec_locate_sorted_groups()` is similar to `vec_group_loc()`, except keys
#' # are returned ordered rather than by first appearance.
#' vec_locate_sorted_groups(df)
#'
#' vec_group_loc(df)
vec_locate_sorted_groups <- function(x,
...,
direction = "asc",
na_value = "largest",
nan_distinct = FALSE,
chr_proxy_collate = NULL) {
check_dots_empty0(...)
.Call(
vctrs_locate_sorted_groups,
x,
direction,
na_value,
nan_distinct,
chr_proxy_collate
)
}
# ------------------------------------------------------------------------------
vec_order_info <- function(x,
...,
direction = "asc",
na_value = "largest",
nan_distinct = FALSE,
chr_proxy_collate = NULL,
chr_ordered = TRUE) {
check_dots_empty0(...)
.Call(vctrs_order_info, x, direction, na_value, nan_distinct, chr_proxy_collate, chr_ordered)
}
# ------------------------------------------------------------------------------
#' Order and sort vectors
#'
#' @inheritParams rlang::args_dots_empty
#'
#' @param x A vector
#' @param direction Direction to sort in. Defaults to `asc`ending.
#' @param na_value Should `NA`s be treated as the largest or smallest values?
#' @return
#' * `vec_order()` an integer vector the same size as `x`.
#' * `vec_sort()` a vector with the same size and type as `x`.
#'
#' @section Differences with `order()`:
#' Unlike the `na.last` argument of `order()` which decides the
#' positions of missing values irrespective of the `decreasing`
#' argument, the `na_value` argument of `vec_order()` interacts with
#' `direction`. If missing values are considered the largest value,
#' they will appear last in ascending order, and first in descending
#' order.
#'
#' @section Dependencies of `vec_order()`:
#' * [vec_proxy_order()]
#'
#' @section Dependencies of `vec_sort()`:
#' * [vec_proxy_order()]
#' * [vec_order()]
#' * [vec_slice()]
#' @export
#' @examples
#' x <- round(c(runif(9), NA), 3)
#' vec_order(x)
#' vec_sort(x)
#' vec_sort(x, direction = "desc")
#'
#' # Can also handle data frames
#' df <- data.frame(g = sample(2, 10, replace = TRUE), x = x)
#' vec_order(df)
#' vec_sort(df)
#' vec_sort(df, direction = "desc")
#'
#' # Missing values interpreted as largest values are last when
#' # in increasing order:
#' vec_order(c(1, NA), na_value = "largest", direction = "asc")
#' vec_order(c(1, NA), na_value = "largest", direction = "desc")
vec_order <- function(x,
...,
direction = c("asc", "desc"),
na_value = c("largest", "smallest")) {
check_dots_empty0(...)
direction <- arg_match0(direction, c("asc", "desc"))
na_value <- arg_match0(na_value, c("largest", "smallest"))
decreasing <- !identical(direction, "asc")
na.last <- identical(na_value, "largest")
if (decreasing) {
na.last <- !na.last
}
proxy <- vec_proxy_order(x)
if (is.data.frame(proxy)) {
if (length(proxy) == 0L) {
# Work around type-instability in `base::order()`
return(vec_seq_along(proxy))
}
args <- map(unstructure(proxy), function(.x) {
if (is.data.frame(.x)) {
.x <- order(vec_order(.x, direction = direction, na_value = na_value))
}
.x
})
exec("order", !!!args, decreasing = decreasing, na.last = na.last)
} else if (is_character(proxy) || is_logical(proxy) || is_integer(proxy) || is_double(proxy) || is.complex(proxy)) {
if (is.object(proxy)) {
proxy <- unstructure(proxy)
}
order(proxy, decreasing = decreasing, na.last = na.last)
} else {
abort("Invalid type returned by `vec_proxy_order()`.")
}
}
#' @export
#' @rdname vec_order
vec_sort <- function(x,
...,
direction = c("asc", "desc"),
na_value = c("largest", "smallest")) {
check_dots_empty0(...)
direction <- arg_match0(direction, c("asc", "desc"))
na_value <- arg_match0(na_value, c("largest", "smallest"))
idx <- vec_order(x, direction = direction, na_value = na_value)
vec_slice(x, idx)
}
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/order.R
|
#' Partially specify a factor
#'
#' @description
#' `r lifecycle::badge("experimental")`
#'
#' This special class can be passed as a `ptype` in order to specify that the
#' result should be a factor that contains at least the specified levels.
#'
#' @inheritParams new_factor
#' @keywords internal
#' @export
#' @examples
#' pf <- partial_factor(levels = c("x", "y"))
#' pf
#'
#' vec_ptype_common(factor("v"), factor("w"), .ptype = pf)
#'
partial_factor <- function(levels = character()) {
partial <- new_factor(levels = levels)
new_partial_factor(partial)
}
new_partial_factor <- function(partial = factor(), learned = factor()) {
stopifnot(
is.factor(partial),
is.factor(learned)
)
# Fails if `learned` is not compatible with `partial`
vec_ptype2(partial, learned)
new_partial(
partial = partial,
learned = learned,
class = "vctrs_partial_factor"
)
}
#' @export
vec_ptype_full.vctrs_partial_factor <- function(x, ...) {
empty <- ""
levels <- map(x, levels)
hashes <- map_chr(levels, hash_label)
needs_indent <- hashes != empty
hashes[needs_indent] <- map_chr(hashes[needs_indent], function(x) paste0(" ", x))
source <- rep_named(names(hashes), empty)
if (hashes["partial"] != empty) {
source["partial"] <- " {partial}"
}
details <- paste0(hashes, source)
details <- details[details != empty]
paste0(
"partial_factor<\n",
paste0(details, collapse = "\n"),
"\n>"
)
}
#' @export
vec_ptype_abbr.vctrs_partial_factor <- function(x, ...) {
"prtl_fctr"
}
#' @method vec_ptype2 vctrs_partial_factor
#' @export
vec_ptype2.vctrs_partial_factor <- function(x, y, ...) {
UseMethod("vec_ptype2.vctrs_partial_factor")
}
#' @method vec_ptype2.vctrs_partial_factor vctrs_partial_factor
#' @export
vec_ptype2.vctrs_partial_factor.vctrs_partial_factor <- function(x, y, ...) {
partial <- vec_ptype2(x$partial, y$partial)
learned <- vec_ptype2(x$learned, y$learned)
new_partial_factor(partial, learned)
}
#' @method vec_ptype2.vctrs_partial_factor factor
#' @export
vec_ptype2.vctrs_partial_factor.factor <- function(x, y, ...) {
new_partial_factor(x$partial, vec_ptype2(x$learned, y))
}
#' @method vec_ptype2.factor vctrs_partial_factor
#' @export
vec_ptype2.factor.vctrs_partial_factor <- function(x, y, ...) {
new_partial_factor(y$partial, vec_ptype2(y$learned, x))
}
#' @export
vec_ptype_finalise.vctrs_partial_factor <- function(x, ...) {
vec_ptype2(x$learned, x$partial)
}
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/partial-factor.R
|
#' Partially specify columns of a data frame
#'
#' @description
#' `r lifecycle::badge("experimental")`
#'
#' This special class can be passed to `.ptype` in order to specify the
#' types of only some of the columns in a data frame.
#'
#' @param ... Attributes of subclass
#' @keywords internal
#' @export
#' @examples
#' pf <- partial_frame(x = double())
#' pf
#'
#' vec_rbind(
#' data.frame(x = 1L, y = "a"),
#' data.frame(x = FALSE, z = 10),
#' .ptype = partial_frame(x = double(), a = character())
#' )
partial_frame <- function(...) {
args <- list2(...)
args <- lapply(args, vec_ptype)
partial <- new_data_frame(args, n = 0L)
new_partial_frame(partial)
}
new_partial_frame <- function(partial = data.frame(), learned = data.frame()) {
stopifnot(
is.data.frame(partial),
is.data.frame(learned)
)
# Fails if `learned` is not compatible with `partial`
vec_ptype2(partial, learned)
new_partial(
partial = partial,
learned = learned,
class = "vctrs_partial_frame"
)
}
#' @export
vec_ptype_full.vctrs_partial_frame <- function(x, ...) {
both <- c(as.list(x$partial), as.list(x$learned))
types <- map_chr(both, vec_ptype_full)
needs_indent <- grepl("\n", types)
types[needs_indent] <- map(types[needs_indent], function(x) indent(paste0("\n", x), 4))
source <- c(rep(" {partial}", length(x$partial)), rep("", length(x$learned)))
names <- paste0(" ", format(names(both)))
paste0(
"partial_frame<\n",
paste0(names, ": ", types, source, collapse = "\n"),
"\n>"
)
}
#' @export
vec_ptype_abbr.vctrs_partial_frame <- function(x, ...) {
"prtl"
}
#' @method vec_ptype2 vctrs_partial_frame
#' @export
vec_ptype2.vctrs_partial_frame <- function(x, y, ...) {
UseMethod("vec_ptype2.vctrs_partial_frame")
}
#' @method vec_ptype2.vctrs_partial_frame vctrs_partial_frame
#' @export
vec_ptype2.vctrs_partial_frame.vctrs_partial_frame <- function(x, y, ...) {
partial <- vec_ptype2(x$partial, y$partial)
learned <- vec_ptype2(x$learned, y$learned)
new_partial_frame(partial, learned)
}
#' @method vec_ptype2.vctrs_partial_frame data.frame
#' @export
vec_ptype2.vctrs_partial_frame.data.frame <- function(x, y, ...) {
new_partial_frame(x$partial, vec_ptype2(x$learned, y))
}
#' @method vec_ptype2.data.frame vctrs_partial_frame
#' @export
vec_ptype2.data.frame.vctrs_partial_frame <- function(x, y, ...) {
new_partial_frame(y$partial, vec_ptype2(y$learned, x))
}
#' @export
vec_ptype_finalise.vctrs_partial_frame <- function(x, ...) {
out <- x$learned
out[names(x$partial)] <- x$partial
out
}
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/partial-frame.R
|
#' Partial type
#'
#' @description
#' `r lifecycle::badge("experimental")`
#'
#' Use `new_partial()` when constructing a new partial type subclass;
#' and use `is_partial()` to test if a type is partial. All subclasses
#' need to provide a `vec_ptype_finalise()` method.
#'
#' @details
#' As the name suggests, a partial type _partially_ specifies a type, and
#' it must be combined with data to yield a full type. A useful example
#' of a partial type is [partial_frame()], which makes it possible to
#' specify the type of just a few columns in a data frame. Use this constructor
#' if you're making your own partial type.
#'
#' @param ... Attributes of the partial type
#' @param class Name of subclass.
#' @export
#' @keywords internal
new_partial <- function(..., class = character()) {
new_sclr(..., class = c(class, "vctrs_partial"))
}
#' @export
obj_print_header.vctrs_partial <- function(x, ...) {
NULL
invisible(x)
}
#' @export
obj_print_data.vctrs_partial <- function(x, ...) {
cat_line(vec_ptype_full(x))
invisible(x)
}
#' @rdname new_partial
#' @export
is_partial <- function(x) {
.Call(ffi_is_partial, x)
}
#' @rdname new_partial
#' @inheritParams rlang::args_dots_empty
#' @export
vec_ptype_finalise <- function(x, ...) {
check_dots_empty0(...)
return(.Call(vctrs_ptype_finalise, x))
UseMethod("vec_ptype_finalise")
}
vec_ptype_finalise_dispatch <- function(x, ...) {
UseMethod("vec_ptype_finalise")
}
#' @export
vec_ptype_finalise.vctrs_partial <- function(x, ...) {
# nocov start
stop_unimplemented(x, "vec_ptype_finalise")
# nocov end
}
#' @export
vec_ptype_finalise.default <- function(x, ...) {
x
}
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/partial.R
|
# print -------------------------------------------------------------------
#' `print()` and `str()` generics.
#'
#' These are constructed to be more easily extensible since you can override
#' the `_header()`, `_data()` or `_footer()` components individually. The
#' default methods are built on top of `format()`.
#'
#' @param x A vector
#' @param ... Additional arguments passed on to methods. See [print()] and
#' [str()] for commonly used options
#' @keywords internal
#' @export
obj_print <- function(x, ...) {
obj_print_header(x, ...)
obj_print_data(x, ...)
obj_print_footer(x, ...)
invisible(x)
}
#' @export
#' @rdname obj_print
obj_print_header <- function(x, ...) {
UseMethod("obj_print_header")
}
#' @export
obj_print_header.default <- function(x, ...) {
cat_line("<", vec_ptype_full(x), "[", vec_size(x), "]>")
invisible(x)
}
#' @export
#' @rdname obj_print
obj_print_data <- function(x, ...) {
UseMethod("obj_print_data")
}
#' @export
obj_print_data.default <- function(x, ...) {
if (length(x) == 0)
return(invisible(x))
out <- stats::setNames(format(x), names(x))
print(out, quote = FALSE)
invisible(x)
}
#' @export
#' @rdname obj_print
obj_print_footer <- function(x, ...) {
UseMethod("obj_print_footer")
}
#' @export
obj_print_footer.default <- function(x, ...) {
invisible(x)
}
# str ---------------------------------------------------------------------
#' @export
#' @rdname obj_print
obj_str <- function(x, ...) {
obj_str_header(x, ...)
obj_str_data(x, ...)
obj_str_footer(x, ...)
}
#' @export
#' @rdname obj_print
obj_str_header <- function(x, ...) {
UseMethod("obj_str_header")
}
#' @export
obj_str_header.default <- function(x, ...) {
invisible(x)
}
#' @export
#' @rdname obj_print
obj_str_data <- function(x, ...) {
UseMethod("obj_str_data")
}
#' @export
obj_str_data.default <- function(x, ...) {
if (is.list(x)) {
obj_str_recursive(x, ...)
} else {
obj_str_leaf(x, ...)
}
}
obj_str_recursive <- function(x, ...,
indent.str = "",
nest.lev = 0) {
if (nest.lev != 0L)
cat(" ")
cat_line(glue::glue("{vec_ptype_abbr(x)} [1:{vec_size(x)}] "))
utils::str(
vec_data(x),
no.list = TRUE,
...,
nest.lev = nest.lev + 1L,
indent.str = indent.str
)
}
obj_str_leaf <- function(x, ...,
indent.str = "",
width = getOption("width")) {
width <- width - nchar(indent.str) - 2
# Avoid spending too much time formatting elements that won't see
length <- ceiling(width / 2)
if (length(x) > length) {
out <- x[seq2(1, length)]
} else {
out <- x
}
title <- glue::glue(" {vec_ptype_abbr(x)} [1:{length(x)}] ")
cat_line(inline_list(title, format(out), width = width))
invisible(x)
}
#' @export
#' @rdname obj_print
obj_str_footer <- function(x, ...) {
UseMethod("obj_str_footer")
}
#' @export
obj_str_footer.default <- function(x, ...,
indent.str = "",
nest.lev = 0) {
attr <- attributes(x)
attr[["class"]] <- NULL
attr[["names"]] <- NULL
if (length(attr) == 0)
return(invisible(x))
if (!is.list(x)) {
indent.str <- paste0(" ", indent.str)
}
utils::str(
attr,
no.list = TRUE,
...,
comp.str = "@ ",
nest.lev = nest.lev + 1L,
indent.str = indent.str
)
invisible(x)
}
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/print-str.R
|
#' Proxy and restore
#'
#' @description
#'
#' `r lifecycle::badge("experimental")`
#'
#' `vec_proxy()` returns the data structure containing the values of a
#' vector. This data structure is usually the vector itself. In this
#' case the proxy is the [identity function][base::identity], which is
#' the default `vec_proxy()` method.
#'
#' Only experts should implement special `vec_proxy()` methods, for
#' these cases:
#'
#' - A vector has vectorised attributes, i.e. metadata for
#' each element of the vector. These _record types_ are implemented
#' in vctrs by returning a data frame in the proxy method. If you're
#' starting your class from scratch, consider deriving from the
#' [`rcrd`][new_rcrd] class. It implements the appropriate data
#' frame proxy and is generally the preferred way to create a record
#' class.
#'
#' - When you're implementing a vector on top of a non-vector type,
#' like an environment or an S4 object. This is currently only
#' partially supported.
#'
#' - S3 lists are considered scalars by default. This is the safe
#' choice for list objects such as returned by `stats::lm()`. To
#' declare that your S3 list class is a vector, you normally add
#' `"list"` to the right of your class vector. Explicit inheritance
#' from list is generally the preferred way to declare an S3 list in
#' R, for instance it makes it possible to dispatch on
#' `generic.list` S3 methods.
#'
#' If you can't modify your class vector, you can implement an
#' identity proxy (i.e. a proxy method that just returns its input)
#' to let vctrs know this is a vector list and not a scalar.
#'
#' `vec_restore()` is the inverse operation of `vec_proxy()`. It
#' should only be called on vector proxies.
#'
#' - It undoes the transformations of `vec_proxy()`.
#'
#' - It restores attributes and classes. These may be lost when the
#' memory values are manipulated. For example slicing a subset of a
#' vector's proxy causes a new proxy to be allocated.
#'
#' By default vctrs restores all attributes and classes
#' automatically. You only need to implement a `vec_restore()` method
#' if your class has attributes that depend on the data.
#'
#' @param x A vector.
#' @inheritParams rlang::args_dots_empty
#'
#' @section Proxying:
#'
#' You should only implement `vec_proxy()` when your type is designed
#' around a non-vector class. I.e. anything that is not either:
#'
#' * An atomic vector
#' * A bare list
#' * A data frame
#'
#' In this case, implement `vec_proxy()` to return such a vector
#' class. The vctrs operations such as [vec_slice()] are applied on
#' the proxy and `vec_restore()` is called to restore the original
#' representation of your type.
#'
#' The most common case where you need to implement `vec_proxy()` is
#' for S3 lists. In vctrs, S3 lists are treated as scalars by
#' default. This way we don't treat objects like model fits as
#' vectors. To prevent vctrs from treating your S3 list as a scalar,
#' unclass it in the `vec_proxy()` method. For instance, here is the
#' definition for `list_of`:
#'
#' ```
#' vec_proxy.vctrs_list_of <- function(x) {
#' unclass(x)
#' }
#' ```
#'
#' Another case where you need to implement a proxy is [record
#' types][new_rcrd]. Record types should return a data frame, as in
#' the `POSIXlt` method:
#'
#' ```
#' vec_proxy.POSIXlt <- function(x) {
#' new_data_frame(unclass(x))
#' }
#' ```
#'
#' Note that you don't need to implement `vec_proxy()` when your class
#' inherits from `vctrs_vctr` or `vctrs_rcrd`.
#'
#'
#' @section Restoring:
#'
#' A restore is a specialised type of cast, primarily used in
#' conjunction with `NextMethod()` or a C-level function that works on
#' the underlying data structure. A `vec_restore()` method can make
#' the following assumptions about `x`:
#'
#' * It has the correct type.
#' * It has the correct names.
#' * It has the correct `dim` and `dimnames` attributes.
#' * It is unclassed. This way you can call vctrs generics with `x`
#' without triggering an infinite loop of restoration.
#'
#' The length may be different (for example after [vec_slice()] has
#' been called), and all other attributes may have been lost. The
#' method should restore all attributes so that after restoration,
#' `vec_restore(vec_data(x), x)` yields `x`.
#'
#' To understand the difference between `vec_cast()` and `vec_restore()`
#' think about factors: it doesn't make sense to cast an integer to a factor,
#' but if `NextMethod()` or another low-level function has stripped attributes,
#' you still need to be able to restore them.
#'
#' The default method copies across all attributes so you only need to
#' provide your own method if your attributes require special care
#' (i.e. they are dependent on the data in some way). When implementing
#' your own method, bear in mind that many R users add attributes to track
#' additional metadata that is important to them, so you should preserve any
#' attributes that don't require special handling for your class.
#'
#' @section Dependencies:
#' - `x` must be a vector in the vctrs sense (see [vec_is()])
#' - By default the underlying data is returned as is (identity proxy)
#'
#' All vector classes have a proxy, even those who don't implement any
#' vctrs methods. The exception is S3 lists that don't inherit from
#' `"list"` explicitly. These might have to implement an identity
#' proxy for compatibility with vctrs (see discussion above).
#'
#' @keywords internal
#' @export
vec_proxy <- function(x, ...) {
check_dots_empty0(...)
return(.Call(ffi_vec_proxy, x))
UseMethod("vec_proxy")
}
#' @export
vec_proxy.default <- function(x, ...) {
x
}
#' @rdname vec_proxy
#' @param to The original vector to restore to.
#' @export
vec_restore <- function(x, to, ...) {
check_dots_empty0(...)
return(.Call(ffi_vec_restore, x, to))
UseMethod("vec_restore", to)
}
vec_restore_dispatch <- function(x, to, ...) {
UseMethod("vec_restore", to)
}
#' @export
vec_restore.default <- function(x, to, ...) {
.Call(ffi_vec_restore_default, x, to)
}
vec_restore_default <- function(x, to, ...) {
.Call(ffi_vec_restore_default, x, to)
}
vec_proxy_recurse <- function(x, ...) {
.Call(ffi_vec_proxy_recurse, x)
}
vec_restore_recurse <- function(x, to, ...) {
.Call(ffi_vec_restore_recurse, x, to)
}
#' Extract underlying data
#'
#' @description
#'
#' `r lifecycle::badge("experimental")`
#'
#' Extract the data underlying an S3 vector object, i.e. the underlying
#' (named) atomic vector, data frame, or list.
#'
#' @param x A vector or object implementing `vec_proxy()`.
#' @return The data underlying `x`, free from any attributes except the names.
#'
#' @section Difference with `vec_proxy()`:
#'
#' * `vec_data()` returns unstructured data. The only attributes
#' preserved are names, dims, and dimnames.
#'
#' Currently, due to the underlying memory architecture of R, this
#' creates a full copy of the data for atomic vectors.
#'
#' * `vec_proxy()` may return structured data. This generic is the
#' main customisation point for accessing memory values in vctrs,
#' along with [vec_restore()].
#'
#' Methods must return a vector type. Records and data frames will
#' be processed rowwise.
#'
#' @keywords internal
#' @export
vec_data <- function(x) {
obj_check_vector(x)
x <- vec_proxy(x)
if (is.data.frame(x)) {
return(new_data_frame(x, row.names = .row_names_info(x, 0L)))
}
if (has_dim(x)) {
x <- vec_set_attributes(x, list(dim = dim(x), dimnames = dimnames(x)))
} else {
x <- vec_set_attributes(x, list(names = names(x)))
}
# Reset S4 bit in vector-like S4 objects
unset_s4(x)
}
unset_s4 <- function(x) {
.Call(ffi_unset_s4, x)
}
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/proxy.R
|
#' Vector type as a string
#'
#' `vec_ptype_full()` displays the full type of the vector. `vec_ptype_abbr()`
#' provides an abbreviated summary suitable for use in a column heading.
#'
#' @section S3 dispatch:
#' The default method for `vec_ptype_full()` uses the first element of the
#' class vector. Override this method if your class has parameters that should
#' be prominently displayed.
#'
#' The default method for `vec_ptype_abbr()` [abbreviate()]s `vec_ptype_full()`
#' to 8 characters. You should almost always override, aiming for 4-6
#' characters where possible.
#'
#' These arguments are handled by the generic and not passed to methods:
#' * `prefix_named`
#' * `suffix_shape`
#'
#' @param x A vector.
#' @param prefix_named If `TRUE`, add a prefix for named vectors.
#' @param suffix_shape If `TRUE` (the default), append the shape of
#' the vector.
#' @inheritParams rlang::args_dots_empty
#'
#' @keywords internal
#' @return A string.
#' @export
#' @examples
#' cat(vec_ptype_full(1:10))
#' cat(vec_ptype_full(iris))
#'
#' cat(vec_ptype_abbr(1:10))
vec_ptype_full <- function(x, ...) {
check_dots_empty0(...)
# Data frames and their subclasses have internal handling in the
# default method to get the inner types format
method <- s3_method_specific(x, "vec_ptype_full", ns = "vctrs")
return(method(x, ...))
UseMethod("vec_ptype_full")
}
#' @export
#' @rdname vec_ptype_full
vec_ptype_abbr <- function(x, ..., prefix_named = FALSE, suffix_shape = TRUE) {
check_dots_empty0(...)
method <- s3_method_specific(x, "vec_ptype_abbr", ns = "vctrs")
abbr <- method(x, ...)
named <- if ((prefix_named || is_bare_list(x)) && !is.null(vec_names(x))) "named "
shape <- if (suffix_shape) vec_ptype_shape(x)
abbr <- paste0(named, abbr, shape)
return(abbr)
UseMethod("vec_ptype_abbr")
}
#' @export
vec_ptype_full.NULL <- function(x, ...) "NULL"
#' @export
vec_ptype_abbr.NULL <- function(x, ...) "NULL"
# Default: base types and fallback for S3/S4 ------------------------------
#' @export
vec_ptype_full.default <- function(x, ...) {
if (is.data.frame(x)) {
vec_ptype_full_data_frame(x, ...)
} else if (is.object(x)) {
class(x)[[1]]
} else if (is_vector(x)) {
paste0(typeof(x), vec_ptype_shape(x))
} else {
abort("Not a vector.")
}
}
#' @export
vec_ptype_abbr.default <- function(x, ...) {
if (is.object(x)) {
type <- class(x)[[1]]
} else if (is_vector(x)) {
type <- vec_ptype_abbr_bare(x, ...)
} else {
abort("Not a vector.")
}
unname(abbreviate(type, 8))
}
vec_ptype_full_data_frame <- function(x, ...) {
if (length(x) == 0) {
return(paste0(class(x)[[1]], "<>"))
} else if (length(x) == 1) {
return(paste0(class(x)[[1]], "<", names(x), ":", vec_ptype_full(x[[1]]), ">"))
}
# Needs to handle recursion with indenting
types <- map_chr(x, vec_ptype_full)
needs_indent <- grepl("\n", types)
types[needs_indent] <- map(types[needs_indent], function(x) indent(paste0("\n", x), 4))
names <- paste0(" ", format(names(x)))
paste0(
class(x)[[1]], "<\n",
paste0(names, ": ", types, collapse = "\n"),
"\n>"
)
}
vec_ptype_abbr_bare <- function(x, ...) {
switch(typeof(x),
list = "list",
logical = "lgl",
integer = "int",
double = "dbl",
character = "chr",
complex = "cpl",
list = "list",
expression = "expr",
raw = "raw",
typeof(x)
)
}
# Helpers -----------------------------------------------------------------
vec_ptype_shape <- function(x) {
dim <- dim2(x)
if (length(dim) == 1) {
if (is_null(dim(x))) {
""
} else {
"[1d]"
}
} else {
paste0("[,", paste(dim[-1], collapse = ","), "]")
}
}
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/ptype-abbr-full.R
|
#' Compute ranks
#'
#' `vec_rank()` computes the sample ranks of a vector. For data frames, ranks
#' are computed along the rows, using all columns after the first to break
#' ties.
#'
#' @details
#' Unlike [base::rank()], when `incomplete = "rank"` all missing values are
#' given the same rank, rather than an increasing sequence of ranks. When
#' `nan_distinct = FALSE`, `NaN` values are given the same rank as `NA`,
#' otherwise they are given a rank that differentiates them from `NA`.
#'
#' Like [vec_order_radix()], ordering is done in the C-locale. This can affect
#' the ranks of character vectors, especially regarding how uppercase and
#' lowercase letters are ranked. See the documentation of [vec_order_radix()]
#' for more information.
#'
#' @inheritParams order-radix
#' @inheritParams rlang::args_dots_empty
#'
#' @param ties Ranking of duplicate values.
#' - `"min"`: Use the current rank for all duplicates. The next non-duplicate
#' value will have a rank incremented by the number of duplicates present.
#'
#' - `"max"`: Use the current rank `+ n_duplicates - 1` for all duplicates.
#' The next non-duplicate value will have a rank incremented by the number of
#' duplicates present.
#'
#' - `"sequential"`: Use an increasing sequence of ranks starting at the
#' current rank, applied to duplicates in order of appearance.
#'
#' - `"dense"`: Use the current rank for all duplicates. The next
#' non-duplicate value will have a rank incremented by `1`, effectively
#' removing any gaps in the ranking.
#'
#' @param incomplete Ranking of missing and [incomplete][vec_detect_complete]
#' observations.
#'
#' - `"rank"`: Rank incomplete observations normally. Missing values within
#' incomplete observations will be affected by `na_value` and `nan_distinct`.
#'
#' - `"na"`: Don't rank incomplete observations at all. Instead, they are
#' given a rank of `NA`. In this case, `na_value` and `nan_distinct` have
#' no effect.
#'
#' @section Dependencies:
#'
#' - [vec_order_radix()]
#' - [vec_slice()]
#'
#' @export
#' @examples
#' x <- c(5L, 6L, 3L, 3L, 5L, 3L)
#'
#' vec_rank(x, ties = "min")
#' vec_rank(x, ties = "max")
#'
#' # Sequential ranks use an increasing sequence for duplicates
#' vec_rank(x, ties = "sequential")
#'
#' # Dense ranks remove gaps between distinct values,
#' # even if there are duplicates
#' vec_rank(x, ties = "dense")
#'
#' y <- c(NA, x, NA, NaN)
#'
#' # Incomplete values match other incomplete values by default, and their
#' # overall position can be adjusted with `na_value`
#' vec_rank(y, na_value = "largest")
#' vec_rank(y, na_value = "smallest")
#'
#' # NaN can be ranked separately from NA if required
#' vec_rank(y, nan_distinct = TRUE)
#'
#' # Rank in descending order. Since missing values are the largest value,
#' # they are given a rank of `1` when ranking in descending order.
#' vec_rank(y, direction = "desc", na_value = "largest")
#'
#' # Give incomplete values a rank of `NA` by setting `incomplete = "na"`
#' vec_rank(y, incomplete = "na")
#'
#' # Can also rank data frames, using columns after the first to break ties
#' z <- c(2L, 3L, 4L, 4L, 5L, 2L)
#' df <- data_frame(x = x, z = z)
#' df
#'
#' vec_rank(df)
vec_rank <- function(x,
...,
ties = c("min", "max", "sequential", "dense"),
incomplete = c("rank", "na"),
direction = "asc",
na_value = "largest",
nan_distinct = FALSE,
chr_proxy_collate = NULL) {
check_dots_empty0(...)
ties <- arg_match0(ties, c("min", "max", "sequential", "dense"), "ties")
incomplete <- arg_match0(incomplete, c("rank", "na"), "incomplete")
.Call(
vctrs_rank,
x,
ties,
incomplete,
direction,
na_value,
nan_distinct,
chr_proxy_collate
)
}
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/rank.R
|
#' Vector recycling
#'
#' `vec_recycle(x, size)` recycles a single vector to a given size.
#' `vec_recycle_common(...)` recycles multiple vectors to their common size. All
#' functions obey the [vctrs recycling rules][theory-faq-recycling], and will
#' throw an error if recycling is not possible. See [vec_size()] for the precise
#' definition of size.
#'
#' @inheritParams rlang::args_error_context
#'
#' @param x A vector to recycle.
#' @param ... Depending on the function used:
#' * For `vec_recycle_common()`, vectors to recycle.
#' * For `vec_recycle()`, these dots should be empty.
#' @param size Desired output size.
#' @param .size Desired output size. If omitted,
#' will use the common size from [vec_size_common()].
#' @param x_arg Argument name for `x`. These are used in error
#' messages to inform the user about which argument has an
#' incompatible size.
#'
#' @section Dependencies:
#' - [vec_slice()]
#'
#' @export
#' @examples
#' # Inputs with 1 observation are recycled
#' vec_recycle_common(1:5, 5)
#' vec_recycle_common(integer(), 5)
#' \dontrun{
#' vec_recycle_common(1:5, 1:2)
#' }
#'
#' # Data frames and matrices are recycled along their rows
#' vec_recycle_common(data.frame(x = 1), 1:5)
#' vec_recycle_common(array(1:2, c(1, 2)), 1:5)
#' vec_recycle_common(array(1:3, c(1, 3, 1)), 1:5)
vec_recycle <- function(x, size, ..., x_arg = "", call = caller_env()) {
check_dots_empty0(...)
.Call(ffi_recycle, x, size, environment())
}
#' @export
#' @rdname vec_recycle
vec_recycle_common <- function(...,
.size = NULL,
.arg = "",
.call = caller_env()) {
.External2(ffi_recycle_common, .size)
}
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/recycle.R
|
# This source code file is licensed under the unlicense license
# https://unlicense.org
#' Register a method for a suggested dependency
#'
#' Generally, the recommend way to register an S3 method is to use the
#' `S3Method()` namespace directive (often generated automatically by the
#' `@export` roxygen2 tag). However, this technique requires that the generic
#' be in an imported package, and sometimes you want to suggest a package,
#' and only provide a method when that package is loaded. `s3_register()`
#' can be called from your package's `.onLoad()` to dynamically register
#' a method only if the generic's package is loaded.
#'
#' For R 3.5.0 and later, `s3_register()` is also useful when demonstrating
#' class creation in a vignette, since method lookup no longer always involves
#' the lexical scope. For R 3.6.0 and later, you can achieve a similar effect
#' by using "delayed method registration", i.e. placing the following in your
#' `NAMESPACE` file:
#'
#' ```
#' if (getRversion() >= "3.6.0") {
#' S3method(package::generic, class)
#' }
#' ```
#'
#' @section Usage in other packages:
#' To avoid taking a dependency on vctrs, you copy the source of
#' [`s3_register()`](https://github.com/r-lib/vctrs/blob/main/R/register-s3.R)
#' into your own package. It is licensed under the permissive
#' [unlicense](https://choosealicense.com/licenses/unlicense/) to make it
#' crystal clear that we're happy for you to do this. There's no need to include
#' the license or even credit us when using this function.
#'
#' @usage NULL
#' @param generic Name of the generic in the form `pkg::generic`.
#' @param class Name of the class
#' @param method Optionally, the implementation of the method. By default,
#' this will be found by looking for a function called `generic.class`
#' in the package environment.
#'
#' Note that providing `method` can be dangerous if you use
#' devtools. When the namespace of the method is reloaded by
#' `devtools::load_all()`, the function will keep inheriting from
#' the old namespace. This might cause crashes because of dangling
#' `.Call()` pointers.
#' @export
#' @examples
#' # A typical use case is to dynamically register tibble/pillar methods
#' # for your class. That way you avoid creating a hard dependency on packages
#' # that are not essential, while still providing finer control over
#' # printing when they are used.
#'
#' .onLoad <- function(...) {
#' s3_register("pillar::pillar_shaft", "vctrs_vctr")
#' s3_register("tibble::type_sum", "vctrs_vctr")
#' }
#' @keywords internal
# nocov start
s3_register <- function(generic, class, method = NULL) {
stopifnot(is.character(generic), length(generic) == 1)
stopifnot(is.character(class), length(class) == 1)
pieces <- strsplit(generic, "::")[[1]]
stopifnot(length(pieces) == 2)
package <- pieces[[1]]
generic <- pieces[[2]]
caller <- parent.frame()
get_method_env <- function() {
top <- topenv(caller)
if (isNamespace(top)) {
asNamespace(environmentName(top))
} else {
caller
}
}
get_method <- function(method) {
if (is.null(method)) {
get(paste0(generic, ".", class), envir = get_method_env())
} else {
method
}
}
register <- function(...) {
envir <- asNamespace(package)
# Refresh the method each time, it might have been updated by
# `devtools::load_all()`
method_fn <- get_method(method)
stopifnot(is.function(method_fn))
# Only register if generic can be accessed
if (exists(generic, envir)) {
registerS3method(generic, class, method_fn, envir = envir)
} else if (identical(Sys.getenv("NOT_CRAN"), "true")) {
warn <- .rlang_s3_register_compat("warn")
warn(c(
sprintf(
"Can't find generic `%s` in package %s to register S3 method.",
generic,
package
),
"i" = "This message is only shown to developers using devtools.",
"i" = sprintf("Do you need to update %s to the latest version?", package)
))
}
}
# Always register hook in case package is later unloaded & reloaded
setHook(packageEvent(package, "onLoad"), function(...) {
register()
})
# For compatibility with R < 4.0 where base isn't locked
is_sealed <- function(pkg) {
identical(pkg, "base") || environmentIsLocked(asNamespace(pkg))
}
# Avoid registration failures during loading (pkgload or regular).
# Check that environment is locked because the registering package
# might be a dependency of the package that exports the generic. In
# that case, the exports (and the generic) might not be populated
# yet (#1225).
if (isNamespaceLoaded(package) && is_sealed(package)) {
register()
}
invisible()
}
.rlang_s3_register_compat <- function(fn, try_rlang = TRUE) {
# Compats that behave the same independently of rlang's presence
out <- switch(
fn,
is_installed = return(function(pkg) requireNamespace(pkg, quietly = TRUE))
)
# Only use rlang if it is fully loaded (#1482)
if (try_rlang &&
requireNamespace("rlang", quietly = TRUE) &&
environmentIsLocked(asNamespace("rlang"))) {
switch(
fn,
is_interactive = return(rlang::is_interactive)
)
# Make sure rlang knows about "x" and "i" bullets
if (utils::packageVersion("rlang") >= "0.4.2") {
switch(
fn,
abort = return(rlang::abort),
warn = return((rlang::warn)),
inform = return(rlang::inform)
)
}
}
# Fall back to base compats
is_interactive_compat <- function() {
opt <- getOption("rlang_interactive")
if (!is.null(opt)) {
opt
} else {
interactive()
}
}
format_msg <- function(x) paste(x, collapse = "\n")
switch(
fn,
is_interactive = return(is_interactive_compat),
abort = return(function(msg) stop(format_msg(msg), call. = FALSE)),
warn = return(function(msg) warning(format_msg(msg), call. = FALSE)),
inform = return(function(msg) message(format_msg(msg)))
)
stop(sprintf("Internal error in rlang shims: Unknown function `%s()`.", fn))
}
on_load({
s3_register <- replace_from("s3_register", "rlang")
})
knitr_defer <- function(expr, env = caller_env()) {
roxy_caller <- detect(sys.frames(), env_inherits, ns_env("knitr"))
if (is_null(roxy_caller)) {
abort("Internal error: can't find knitr on the stack.")
}
blast(
withr::defer(!!substitute(expr), !!roxy_caller),
env
)
}
blast <- function(expr, env = caller_env()) {
eval_bare(enexpr(expr), env)
}
knitr_local_registration <- function(generic, class, env = caller_env()) {
stopifnot(is.character(generic), length(generic) == 1)
stopifnot(is.character(class), length(class) == 1)
pieces <- strsplit(generic, "::")[[1]]
stopifnot(length(pieces) == 2)
package <- pieces[[1]]
generic <- pieces[[2]]
name <- paste0(generic, ".", class)
method <- env_get(env, name)
old <- env_bind(global_env(), !!name := method)
knitr_defer(env_bind(global_env(), !!!old))
}
# nocov end
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/register-s3.R
|
#' Repeat a vector
#'
#' @description
#' - `vec_rep()` repeats an entire vector a set number of `times`.
#'
#' - `vec_rep_each()` repeats each element of a vector a set number of `times`.
#'
#' - `vec_unrep()` compresses a vector with repeated values. The repeated values
#' are returned as a `key` alongside the number of `times` each key is
#' repeated.
#'
#' @details
#' Using `vec_unrep()` and `vec_rep_each()` together is similar to using
#' [base::rle()] and [base::inverse.rle()]. The following invariant shows
#' the relationship between the two functions:
#'
#' ```
#' compressed <- vec_unrep(x)
#' identical(x, vec_rep_each(compressed$key, compressed$times))
#' ```
#'
#' There are two main differences between `vec_unrep()` and [base::rle()]:
#'
#' - `vec_unrep()` treats adjacent missing values as equivalent, while `rle()`
#' treats them as different values.
#'
#' - `vec_unrep()` works along the size of `x`, while `rle()` works along its
#' length. This means that `vec_unrep()` works on data frames by compressing
#' repeated rows.
#'
#' @inheritParams rlang::args_error_context
#' @inheritParams rlang::args_dots_empty
#' @param x A vector.
#' @param times
#' For `vec_rep()`, a single integer for the number of times to repeat
#' the entire vector.
#'
#' For `vec_rep_each()`, an integer vector of the number of times to repeat
#' each element of `x`. `times` will be [recycled][theory-faq-recycling] to
#' the size of `x`.
#' @param x_arg,times_arg Argument names for errors.
#'
#' @return
#' For `vec_rep()`, a vector the same type as `x` with size
#' `vec_size(x) * times`.
#'
#' For `vec_rep_each()`, a vector the same type as `x` with size
#' `sum(vec_recycle(times, vec_size(x)))`.
#'
#' For `vec_unrep()`, a data frame with two columns, `key` and `times`. `key`
#' is a vector with the same type as `x`, and `times` is an integer vector.
#'
#' @section Dependencies:
#' - [vec_slice()]
#'
#' @name vec-rep
#' @examples
#' # Repeat the entire vector
#' vec_rep(1:2, 3)
#'
#' # Repeat within each vector
#' vec_rep_each(1:2, 3)
#' x <- vec_rep_each(1:2, c(3, 4))
#' x
#'
#' # After using `vec_rep_each()`, you can recover the original vector
#' # with `vec_unrep()`
#' vec_unrep(x)
#'
#' df <- data.frame(x = 1:2, y = 3:4)
#'
#' # `rep()` repeats columns of data frames, and returns lists
#' rep(df, each = 2)
#'
#' # `vec_rep()` and `vec_rep_each()` repeat rows, and return data frames
#' vec_rep(df, 2)
#' vec_rep_each(df, 2)
#'
#' # `rle()` treats adjacent missing values as different
#' y <- c(1, NA, NA, 2)
#' rle(y)
#'
#' # `vec_unrep()` treats them as equivalent
#' vec_unrep(y)
NULL
#' @rdname vec-rep
#' @export
vec_rep <- function(x,
times,
...,
error_call = current_env(),
x_arg = "x",
times_arg = "times") {
check_dots_empty0(...)
.Call(ffi_vec_rep, x, times, environment())
}
#' @rdname vec-rep
#' @export
vec_rep_each <- function(x,
times,
...,
error_call = current_env(),
x_arg = "x",
times_arg = "times") {
check_dots_empty0(...)
.Call(ffi_vec_rep_each, x, times, environment())
}
#' @rdname vec-rep
#' @export
vec_unrep <- function(x) {
.Call(ffi_vec_unrep, x, environment())
}
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/rep.R
|
#' Runs
#'
#' @description
#' - `vec_identify_runs()` returns a vector of identifiers for the elements of
#' `x` that indicate which run of repeated values they fall in. The number of
#' runs is also returned as an attribute, `n`.
#'
#' - `vec_run_sizes()` returns an integer vector corresponding to the size of
#' each run. This is identical to the `times` column from `vec_unrep()`, but
#' is faster if you don't need the run keys.
#'
#' - [vec_unrep()] is a generalized [base::rle()]. It is documented alongside
#' the "repeat" functions of [vec_rep()] and [vec_rep_each()]; look there for
#' more information.
#'
#' @details
#' Unlike [base::rle()], adjacent missing values are considered identical when
#' constructing runs. For example, `vec_identify_runs(c(NA, NA))` will return
#' `c(1, 1)`, not `c(1, 2)`.
#'
#' @param x A vector.
#'
#' @return
#' - For `vec_identify_runs()`, an integer vector with the same size as `x`. A
#' scalar integer attribute, `n`, is attached.
#'
#' - For `vec_run_sizes()`, an integer vector with size equal to the number of
#' runs in `x`.
#'
#' @seealso
#' [vec_unrep()] for a generalized [base::rle()].
#'
#' @name runs
#' @examples
#' x <- c("a", "z", "z", "c", "a", "a")
#'
#' vec_identify_runs(x)
#' vec_run_sizes(x)
#' vec_unrep(x)
#'
#' y <- c(1, 1, 1, 2, 2, 3)
#'
#' # With multiple columns, the runs are constructed rowwise
#' df <- data_frame(
#' x = x,
#' y = y
#' )
#'
#' vec_identify_runs(df)
#' vec_run_sizes(df)
#' vec_unrep(df)
NULL
#' @rdname runs
#' @export
vec_identify_runs <- function(x) {
.Call(ffi_vec_identify_runs, x, environment())
}
#' @rdname runs
#' @export
vec_run_sizes <- function(x) {
.Call(ffi_vec_run_sizes, x, environment())
}
vec_locate_run_bounds <- function(x, which = c("start", "end")) {
.Call(ffi_vec_locate_run_bounds, x, which, environment())
}
vec_detect_run_bounds <- function(x, which = c("start", "end")) {
.Call(ffi_vec_detect_run_bounds, x, which, environment())
}
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/runs.R
|
#' Set operations
#'
#' @description
#' - `vec_set_intersect()` returns all values in both `x` and `y`.
#'
#' - `vec_set_difference()` returns all values in `x` but not `y`. Note
#' that this is an asymmetric set difference, meaning it is not commutative.
#'
#' - `vec_set_union()` returns all values in either `x` or `y`.
#'
#' - `vec_set_symmetric_difference()` returns all values in either `x` or `y`
#' but not both. This is a commutative difference.
#'
#' Because these are _set_ operations, these functions only return unique values
#' from `x` and `y`, returned in the order they first appeared in the original
#' input. Names of `x` and `y` are retained on the result, but names are always
#' taken from `x` if the value appears in both inputs.
#'
#' These functions work similarly to [intersect()], [setdiff()], and [union()],
#' but don't strip attributes and can be used with data frames.
#'
#' @inheritParams rlang::args_dots_empty
#' @inheritParams rlang::args_error_context
#'
#' @param x,y A pair of vectors.
#'
#' @param ptype If `NULL`, the default, the output type is determined by
#' computing the common type between `x` and `y`. If supplied, both `x` and
#' `y` will be cast to this type.
#'
#' @param x_arg,y_arg Argument names for `x` and `y`. These are used in error
#' messages.
#'
#' @returns
#' A vector of the common type of `x` and `y` (or `ptype`, if supplied)
#' containing the result of the corresponding set function.
#'
#' @details
#' Missing values are treated as equal to other missing values. For doubles and
#' complexes, `NaN` are equal to other `NaN`, but not to `NA`.
#'
#' @section Dependencies:
#'
#' ## `vec_set_intersect()`
#' - [vec_proxy_equal()]
#' - [vec_slice()]
#' - [vec_ptype2()]
#' - [vec_cast()]
#'
#' ## `vec_set_difference()`
#' - [vec_proxy_equal()]
#' - [vec_slice()]
#' - [vec_ptype2()]
#' - [vec_cast()]
#'
#' ## `vec_set_union()`
#' - [vec_proxy_equal()]
#' - [vec_slice()]
#' - [vec_ptype2()]
#' - [vec_cast()]
#' - [vec_c()]
#'
#' ## `vec_set_symmetric_difference()`
#' - [vec_proxy_equal()]
#' - [vec_slice()]
#' - [vec_ptype2()]
#' - [vec_cast()]
#' - [vec_c()]
#'
#' @name vec-set
#' @examples
#' x <- c(1, 2, 1, 4, 3)
#' y <- c(2, 5, 5, 1)
#'
#' # All unique values in both `x` and `y`.
#' # Duplicates in `x` and `y` are always removed.
#' vec_set_intersect(x, y)
#'
#' # All unique values in `x` but not `y`
#' vec_set_difference(x, y)
#'
#' # All unique values in either `x` or `y`
#' vec_set_union(x, y)
#'
#' # All unique values in either `x` or `y` but not both
#' vec_set_symmetric_difference(x, y)
#'
#' # These functions can also be used with data frames
#' x <- data_frame(
#' a = c(2, 3, 2, 2),
#' b = c("j", "k", "j", "l")
#' )
#' y <- data_frame(
#' a = c(1, 2, 2, 2, 3),
#' b = c("j", "l", "j", "l", "j")
#' )
#'
#' vec_set_intersect(x, y)
#' vec_set_difference(x, y)
#' vec_set_union(x, y)
#' vec_set_symmetric_difference(x, y)
#'
#' # Vector names don't affect set membership, but if you'd like to force
#' # them to, you can transform the vector into a two column data frame
#' x <- c(a = 1, b = 2, c = 2, d = 3)
#' y <- c(c = 2, b = 1, a = 3, d = 3)
#'
#' vec_set_intersect(x, y)
#'
#' x <- data_frame(name = names(x), value = unname(x))
#' y <- data_frame(name = names(y), value = unname(y))
#'
#' vec_set_intersect(x, y)
NULL
#' @rdname vec-set
#' @export
vec_set_intersect <- function(x,
y,
...,
ptype = NULL,
x_arg = "x",
y_arg = "y",
error_call = current_env()) {
check_dots_empty0(...)
.Call(ffi_vec_set_intersect, x, y, ptype, environment())
}
#' @rdname vec-set
#' @export
vec_set_difference <- function(x,
y,
...,
ptype = NULL,
x_arg = "x",
y_arg = "y",
error_call = current_env()) {
check_dots_empty0(...)
.Call(ffi_vec_set_difference, x, y, ptype, environment())
}
#' @rdname vec-set
#' @export
vec_set_union <- function(x,
y,
...,
ptype = NULL,
x_arg = "x",
y_arg = "y",
error_call = current_env()) {
check_dots_empty0(...)
.Call(ffi_vec_set_union, x, y, ptype, environment())
}
#' @rdname vec-set
#' @export
vec_set_symmetric_difference <- function(x,
y,
...,
ptype = NULL,
x_arg = "x",
y_arg = "y",
error_call = current_env()) {
check_dots_empty0(...)
.Call(ffi_vec_set_symmetric_difference, x, y, ptype, environment())
}
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/set.R
|
# The dimensionality of an matrix/array is partition into two parts:
# * the first dimension = the number of observations
# * all other dimensions = the shape parameter of the type
# These helpers work with the shape parameter
new_shape <- function(type, shape = integer()) {
structure(type, dim = c(0L, shape))
}
vec_shaped_ptype <- function(ptype, x, y, ..., x_arg = "", y_arg = "") {
check_dots_empty0(...)
.Call(ffi_vec_shaped_ptype, ptype, x, y, environment())
}
vec_shape2 <- function(x, y, ..., x_arg = "", y_arg = "") {
check_dots_empty0(...)
.Call(ffi_vec_shape2, x, y, environment())
}
# Should take same signature as `vec_cast()`
shape_broadcast <- function(x,
to,
...,
x_arg,
to_arg,
call = caller_env()) {
if (is.null(x) || is.null(to)) {
return(x)
}
dim_x <- vec_dim(x)
dim_to <- vec_dim(to)
# Don't set dimensions for vectors
if (length(dim_x) == 1L && length(dim_to) == 1L) {
return(x)
}
if (length(dim_x) > length(dim_to)) {
details <- sprintf(
"Can't decrease dimensionality from %s to %s.",
length(dim_x),
length(dim_to)
)
stop_incompatible_cast(
x,
to,
details = details,
x_arg = x_arg,
to_arg = to_arg,
call = call
)
}
dim_x <- n_dim2(dim_x, dim_to)$x
dim_to[[1]] <- dim_x[[1]] # don't change number of observations
ok <- dim_x == dim_to | dim_x == 1
if (any(!ok)) {
stop_incompatible_cast(
x,
to,
details = "Non-recyclable dimensions.",
x_arg = x_arg,
to_arg = to_arg,
call = call
)
}
# Increase dimensionality if required
if (vec_dim_n(x) != length(dim_x)) {
dim(x) <- dim_x
}
recycle <- dim_x != dim_to
# Avoid expensive subset
if (all(!recycle)) {
return(x)
}
indices <- rep(list(missing_arg()), length(dim_to))
indices[recycle] <- map(dim_to[recycle], rep_len, x = 1L)
eval_bare(expr(x[!!!indices, drop = FALSE]))
}
# Helpers -----------------------------------------------------------------
n_dim2 <- function(x, y) {
nx <- length(x)
ny <- length(y)
if (nx == ny) {
list(x = x, y = y)
} else if (nx < ny) {
list(x = c(x, rep(1L, ny - nx)), y = y)
} else {
list(x = x, y = c(y, rep(1L, nx - ny)))
}
}
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/shape.R
|
#' Number of observations
#'
#' @description
#'
#' `vec_size(x)` returns the size of a vector. `vec_is_empty()`
#' returns `TRUE` if the size is zero, `FALSE` otherwise.
#'
#' The size is distinct from the [length()] of a vector because it
#' generalises to the "number of observations" for 2d structures,
#' i.e. it's the number of rows in matrix or a data frame. This
#' definition has the important property that every column of a data
#' frame (even data frame and matrix columns) have the same size.
#' `vec_size_common(...)` returns the common size of multiple vectors.
#'
#' `list_sizes()` returns an integer vector containing the size of each element
#' of a list. It is nearly equivalent to, but faster than,
#' `map_int(x, vec_size)`, with the exception that `list_sizes()` will
#' error on non-list inputs, as defined by [obj_is_list()]. `list_sizes()` is
#' to `vec_size()` as [lengths()] is to [length()].
#'
#' @seealso [vec_slice()] for a variation of `[` compatible with `vec_size()`,
#' and [vec_recycle()] to [recycle][theory-faq-recycling] vectors to common
#' length.
#' @section Invariants:
#' * `vec_size(dataframe)` == `vec_size(dataframe[[i]])`
#' * `vec_size(matrix)` == `vec_size(matrix[, i, drop = FALSE])`
#' * `vec_size(vec_c(x, y))` == `vec_size(x)` + `vec_size(y)`
#'
#' @inheritParams rlang::args_error_context
#'
#' @param x,... Vector inputs or `NULL`.
#' @param .size If `NULL`, the default, the output size is determined by
#' recycling the lengths of all elements of `...`. Alternatively, you can
#' supply `.size` to force a known size; in this case, `x` and `...` are
#' ignored.
#' @param .absent The size used when no input is provided, or when all input
#' is `NULL`. If left as `NULL` when no input is supplied, an error is thrown.
#' @return An integer (or double for long vectors).
#'
#' `vec_size_common()` returns `.absent` if all inputs are `NULL` or
#' absent, `0L` by default.
#'
#'
#' @details
#'
#' There is no vctrs helper that retrieves the number of columns: as this
#' is a property of the [type][vec_ptype_show()].
#'
#' `vec_size()` is equivalent to `NROW()` but has a name that is easier to
#' pronounce, and throws an error when passed non-vector inputs.
#'
#'
#' @section The size of NULL:
#'
#' The size of `NULL` is hard-coded to `0L` in `vec_size()`.
#' `vec_size_common()` returns `.absent` when all inputs are `NULL`
#' (if only some inputs are `NULL`, they are simply ignored).
#'
#' A default size of 0 makes sense because sizes are most often
#' queried in order to compute a total size while assembling a
#' collection of vectors. Since we treat `NULL` as an absent input by
#' principle, we return the identity of sizes under addition to
#' reflect that an absent input doesn't take up any size.
#'
#' Note that other defaults might make sense under different
#' circumstances. For instance, a default size of 1 makes sense for
#' finding the common size because 1 is the identity of the recycling
#' rules.
#'
#' @section Dependencies:
#' - [vec_proxy()]
#'
#' @export
#' @examples
#' vec_size(1:100)
#' vec_size(mtcars)
#' vec_size(array(dim = c(3, 5, 10)))
#'
#' vec_size_common(1:10, 1:10)
#' vec_size_common(1:10, 1)
#' vec_size_common(integer(), 1)
#'
#' list_sizes(list("a", 1:5, letters))
vec_size <- function(x) {
.Call(ffi_size, x, environment())
}
#' @export
#' @rdname vec_size
vec_size_common <- function(...,
.size = NULL,
.absent = 0L,
.arg = "",
.call = caller_env()) {
.External2(ffi_size_common, .size, .absent)
}
#' @rdname vec_size
#' @export
list_sizes <- function(x) {
.Call(ffi_list_sizes, x, environment())
}
#' @rdname vec_size
#' @export
vec_is_empty <- function(x) {
vec_size(x) == 0L
}
#' Default value for empty vectors
#'
#' Use this inline operator when you need to provide a default value for
#' empty (as defined by [vec_is_empty()]) vectors.
#'
#' @param x A vector
#' @param y Value to use if `x` is empty. To preserve type-stability, should
#' be the same type as `x`.
#' @rdname op-empty-default
#' @export
#' @examples
#' 1:10 %0% 5
#' integer() %0% 5
`%0%` <- function(x, y) {
if (vec_is_empty(x)) y else x
}
# sequences -------------------------------------------------------------------
#' Useful sequences
#'
#' `vec_seq_along()` is equivalent to [seq_along()] but uses size, not length.
#' `vec_init_along()` creates a vector of missing values with size matching
#' an existing object.
#'
#' @param x,y Vectors
#' @return
#' * `vec_seq_along()` an integer vector with the same size as `x`.
#' * `vec_init_along()` a vector with the same type as `x` and the same size
#' as `y`.
#' @export
#' @examples
#' vec_seq_along(mtcars)
#' vec_init_along(head(mtcars))
vec_seq_along <- function(x) {
seq_len(vec_size(x))
}
#' @export
#' @rdname vec_seq_along
vec_init_along <- function(x, y = x) {
vec_slice(x, rep_len(NA_integer_, vec_size(y)))
}
vec_as_short_length <- function(n,
arg = caller_arg(n),
call = caller_env()) {
.Call(ffi_as_short_length, n, environment())
}
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/size.R
|
#' Chopping
#'
#' @description
#' - `vec_chop()` provides an efficient method to repeatedly slice a vector. It
#' captures the pattern of `map(indices, vec_slice, x = x)`. When no indices
#' are supplied, it is generally equivalent to [as.list()].
#'
#' - `list_unchop()` combines a list of vectors into a single vector, placing
#' elements in the output according to the locations specified by `indices`.
#' It is similar to [vec_c()], but gives greater control over how the elements
#' are combined. When no indices are supplied, it is identical to `vec_c()`,
#' but typically a little faster.
#'
#' If `indices` selects every value in `x` exactly once, in any order, then
#' `list_unchop()` is the inverse of `vec_chop()` and the following invariant
#' holds:
#'
#' ```
#' list_unchop(vec_chop(x, indices = indices), indices = indices) == x
#' ```
#'
#' @inheritParams rlang::args_dots_empty
#' @inheritParams vec_c
#'
#' @param x A vector
#' @param indices For `vec_chop()`, a list of positive integer vectors to
#' slice `x` with, or `NULL`. Can't be used if `sizes` is already specified.
#' If both `indices` and `sizes` are `NULL`, `x` is split into its individual
#' elements, equivalent to using an `indices` of `as.list(vec_seq_along(x))`.
#'
#' For `list_unchop()`, a list of positive integer vectors specifying the
#' locations to place elements of `x` in. Each element of `x` is recycled to
#' the size of the corresponding index vector. The size of `indices` must
#' match the size of `x`. If `NULL`, `x` is combined in the order it is
#' provided in, which is equivalent to using [vec_c()].
#' @param sizes An integer vector of non-negative sizes representing sequential
#' indices to slice `x` with, or `NULL`. Can't be used if `indices` is already
#' specified.
#'
#' For example, `sizes = c(2, 4)` is equivalent to `indices = list(1:2, 3:6)`,
#' but is typically faster.
#'
#' `sum(sizes)` must be equal to `vec_size(x)`, i.e. `sizes` must completely
#' partition `x`, but an individual size is allowed to be `0`.
#' @param ptype If `NULL`, the default, the output type is determined by
#' computing the common type across all elements of `x`. Alternatively, you
#' can supply `ptype` to give the output a known type.
#' @return
#' - `vec_chop()`: A list where each element has the same type as `x`. The size
#' of the list is equal to `vec_size(indices)`, `vec_size(sizes)`, or
#' `vec_size(x)` depending on whether or not `indices` or `sizes` is provided.
#'
#' - `list_unchop()`: A vector of type `vec_ptype_common(!!!x)`, or `ptype`, if
#' specified. The size is computed as `vec_size_common(!!!indices)` unless
#' the indices are `NULL`, in which case the size is `vec_size_common(!!!x)`.
#'
#' @section Dependencies of `vec_chop()`:
#' - [vec_slice()]
#'
#' @section Dependencies of `list_unchop()`:
#' - [vec_c()]
#'
#' @export
#' @examples
#' vec_chop(1:5)
#'
#' # These two are equivalent
#' vec_chop(1:5, indices = list(1:2, 3:5))
#' vec_chop(1:5, sizes = c(2, 3))
#'
#' # Can also be used on data frames
#' vec_chop(mtcars, indices = list(1:3, 4:6))
#'
#' # If `indices` selects every value in `x` exactly once,
#' # in any order, then `list_unchop()` inverts `vec_chop()`
#' x <- c("a", "b", "c", "d")
#' indices <- list(2, c(3, 1), 4)
#' vec_chop(x, indices = indices)
#' list_unchop(vec_chop(x, indices = indices), indices = indices)
#'
#' # When unchopping, size 1 elements of `x` are recycled
#' # to the size of the corresponding index
#' list_unchop(list(1, 2:3), indices = list(c(1, 3, 5), c(2, 4)))
#'
#' # Names are retained, and outer names can be combined with inner
#' # names through the use of a `name_spec`
#' lst <- list(x = c(a = 1, b = 2), y = 1)
#' list_unchop(lst, indices = list(c(3, 2), c(1, 4)), name_spec = "{outer}_{inner}")
#'
#' # An alternative implementation of `ave()` can be constructed using
#' # `vec_chop()` and `list_unchop()` in combination with `vec_group_loc()`
#' ave2 <- function(.x, .by, .f, ...) {
#' indices <- vec_group_loc(.by)$loc
#' chopped <- vec_chop(.x, indices = indices)
#' out <- lapply(chopped, .f, ...)
#' list_unchop(out, indices = indices)
#' }
#'
#' breaks <- warpbreaks$breaks
#' wool <- warpbreaks$wool
#'
#' ave2(breaks, wool, mean)
#'
#' identical(
#' ave2(breaks, wool, mean),
#' ave(breaks, wool, FUN = mean)
#' )
#'
#' # If you know your input is sorted and you'd like to split on the groups,
#' # `vec_run_sizes()` can be efficiently combined with `sizes`
#' df <- data_frame(
#' g = c(2, 5, 5, 6, 6, 6, 6, 8, 9, 9),
#' x = 1:10
#' )
#' vec_chop(df, sizes = vec_run_sizes(df$g))
#'
#' # If you have a list of homogeneous vectors, sometimes it can be useful to
#' # unchop, apply a function to the flattened vector, and then rechop according
#' # to the original indices. This can be done efficiently with `list_sizes()`.
#' x <- list(c(1, 2, 1), c(3, 1), 5, double())
#' x_flat <- list_unchop(x)
#' x_flat <- x_flat + max(x_flat)
#' vec_chop(x_flat, sizes = list_sizes(x))
vec_chop <- function(x, ..., indices = NULL, sizes = NULL) {
if (!missing(...)) {
indices <- check_dots_chop(..., indices = indices)
}
.Call(ffi_vec_chop, x, indices, sizes)
}
check_dots_chop <- function(..., indices = NULL, call = caller_env()) {
if (!is_null(indices)) {
# Definitely can't supply both `indices` and `...`
check_dots_empty0(..., call = call)
}
if (dots_n(...) != 1L) {
# Backwards compatible case doesn't allow for length >1 `...`.
# This must be an error case.
check_dots_empty0(..., call = call)
}
# TODO: Soft-deprecate this after dplyr/tidyr have updated all `vec_chop()`
# calls to be explicit about `indices =`
# Assume this is an old style `vec_chop(x, indices)` call, before we
# added the `...`
indices <- list(...)[[1L]]
indices
}
#' @rdname vec_chop
#' @export
list_unchop <- function(x,
...,
indices = NULL,
ptype = NULL,
name_spec = NULL,
name_repair = c("minimal", "unique", "check_unique", "universal", "unique_quiet", "universal_quiet"),
error_arg = "x",
error_call = current_env()) {
check_dots_empty0(...)
.Call(ffi_list_unchop, x, indices, ptype, name_spec, name_repair, environment())
}
# Exposed for testing (`starts` is 0-based)
vec_chop_seq <- function(x, starts, sizes, increasings = TRUE) {
args <- vec_recycle_common(starts, sizes, increasings)
.Call(ffi_vec_chop_seq, x, args[[1]], args[[2]], args[[3]])
}
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/slice-chop.R
|
#' Interleave many vectors into one vector
#'
#' @description
#' `vec_interleave()` combines multiple vectors together, much like [vec_c()],
#' but does so in such a way that the elements of each vector are interleaved
#' together.
#'
#' It is a more efficient equivalent to the following usage of `vec_c()`:
#'
#' ```
#' vec_interleave(x, y) == vec_c(x[1], y[1], x[2], y[2], ..., x[n], y[n])
#' ```
#'
#' @section Dependencies:
#'
#' ## vctrs dependencies
#'
#' - [list_unchop()]
#'
#' @inheritParams vec_c
#'
#' @param ... Vectors to interleave. These will be
#' [recycled][theory-faq-recycling] to a common size.
#'
#' @export
#' @examples
#' # The most common case is to interleave two vectors
#' vec_interleave(1:3, 4:6)
#'
#' # But you aren't restricted to just two
#' vec_interleave(1:3, 4:6, 7:9, 10:12)
#'
#' # You can also interleave data frames
#' x <- data_frame(x = 1:2, y = c("a", "b"))
#' y <- data_frame(x = 3:4, y = c("c", "d"))
#'
#' vec_interleave(x, y)
vec_interleave <- function(...,
.ptype = NULL,
.name_spec = NULL,
.name_repair = c("minimal", "unique", "check_unique", "universal", "unique_quiet", "universal_quiet")) {
args <- list2(...)
# `NULL`s must be dropped up front to generate appropriate indices
if (vec_any_missing(args)) {
missing <- vec_detect_missing(args)
args <- vec_slice(args, !missing)
}
n <- length(args)
size <- vec_size_common(!!!args)
indices <- vec_interleave_indices(n, size)
list_unchop(
x = args,
indices = indices,
ptype = .ptype,
name_spec = .name_spec,
name_repair = .name_repair
)
}
vec_interleave_indices <- function(n, size) {
.Call(ffi_interleave_indices, n, size)
}
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/slice-interleave.R
|
#' Get or set observations in a vector
#'
#' This provides a common interface to extracting and modifying observations
#' for all vector types, regardless of dimensionality. It is an analog to `[`
#' that matches [vec_size()] instead of `length()`.
#'
#' @inheritParams rlang::args_dots_empty
#' @inheritParams rlang::args_error_context
#'
#' @param x A vector
#' @param i An integer, character or logical vector specifying the
#' locations or names of the observations to get/set. Specify
#' `TRUE` to index all elements (as in `x[]`), or `NULL`, `FALSE` or
#' `integer()` to index none (as in `x[NULL]`).
#' @param value Replacement values. `value` is cast to the type of
#' `x`, but only if they have a common type. See below for examples
#' of this rule.
#' @param x_arg,value_arg Argument names for `x` and `value`. These are used
#' in error messages to inform the user about the locations of
#' incompatible types and sizes (see [stop_incompatible_type()] and
#' [stop_incompatible_size()]).
#'
#' @return A vector of the same type as `x`.
#'
#' @section Genericity:
#'
#' Support for S3 objects depends on whether the object implements a
#' [vec_proxy()] method.
#'
#' * When a `vec_proxy()` method exists, the proxy is sliced and
#' `vec_restore()` is called on the result.
#'
#' * Otherwise `vec_slice()` falls back to the base generic `[`.
#'
#' Note that S3 lists are treated as scalars by default, and will
#' cause an error if they don't implement a [vec_proxy()] method.
#'
#' @section Differences with base R subsetting:
#'
#' * `vec_slice()` only slices along one dimension. For
#' two-dimensional types, the first dimension is subsetted.
#'
#' * `vec_slice()` preserves attributes by default.
#'
#' * `vec_slice<-()` is type-stable and always returns the same type
#' as the LHS.
#'
#' @section Dependencies:
#'
#' ## vctrs dependencies
#'
#' - [vec_proxy()]
#' - [vec_restore()]
#'
#' ## base dependencies
#'
#' - \code{base::`[`}
#'
#' If a non-data-frame vector class doesn't have a [vec_proxy()]
#' method, the vector is sliced with `[` instead.
#'
#' @export
#' @keywords internal
#' @examples
#' x <- sample(10)
#' x
#' vec_slice(x, 1:3)
#'
#' # You can assign with the infix variant:
#' vec_slice(x, 2) <- 100
#' x
#'
#' # Or with the regular variant that doesn't modify the original input:
#' y <- vec_assign(x, 3, 500)
#' y
#' x
#'
#'
#' # Slicing objects of higher dimension:
#' vec_slice(mtcars, 1:3)
#'
#' # Type stability --------------------------------------------------
#'
#' # The assign variant is type stable. It always returns the same
#' # type as the input.
#' x <- 1:5
#' vec_slice(x, 2) <- 20.0
#'
#' # `x` is still an integer vector because the RHS was cast to the
#' # type of the LHS:
#' vec_ptype(x)
#'
#' # Compare to `[<-`:
#' x[2] <- 20.0
#' vec_ptype(x)
#'
#'
#' # Note that the types must be coercible for the cast to happen.
#' # For instance, you can cast a double vector of whole numbers to an
#' # integer vector:
#' vec_cast(1, integer())
#'
#' # But not fractional doubles:
#' try(vec_cast(1.5, integer()))
#'
#' # For this reason you can't assign fractional values in an integer
#' # vector:
#' x <- 1:3
#' try(vec_slice(x, 2) <- 1.5)
vec_slice <- function(x, i, ..., error_call = current_env()) {
check_dots_empty0(...)
.Call(ffi_slice, x, i, environment())
}
# Called when `x` has dimensions
vec_slice_fallback <- function(x, i) {
out <- unclass(vec_proxy(x))
obj_check_vector(out)
d <- vec_dim_n(out)
if (d == 2) {
out <- out[i, , drop = FALSE]
} else {
miss_args <- rep(list(missing_arg()), d - 1)
out <- eval_bare(expr(out[i, !!!miss_args, drop = FALSE]))
}
vec_restore(out, x)
}
vec_slice_fallback_integer64 <- function(x, i) {
d <- vec_dim_n(x)
if (d == 2) {
out <- x[i, , drop = FALSE]
} else {
miss_args <- rep(list(missing_arg()), d - 1)
out <- eval_bare(expr(x[i, !!!miss_args, drop = FALSE]))
}
is_na <- is.na(i)
if (!any(is_na)) {
return(out)
}
if (d == 2) {
out[is_na,] <- bit64::NA_integer64_
} else {
eval_bare(expr(out[is_na, !!!miss_args] <- bit64::NA_integer64_))
}
out
}
# bit64::integer64() objects do not have support for `NA_integer_`
# slicing. This manually replaces the garbage values that are created
# any time a slice with `NA_integer_` is made.
vec_slice_dispatch_integer64 <- function(x, i) {
out <- x[i]
is_na <- is.na(i)
if (!any(is_na)) {
return(out)
}
out[is_na] <- bit64::NA_integer64_
out
}
#' @rdname vec_slice
#' @export
`vec_slice<-` <- function(x, i, value) {
x_arg <- "" # Substitution is `*tmp*`
delayedAssign("value_arg", as_label(substitute(value)))
.Call(ffi_assign, x, i, value, environment())
}
#' @rdname vec_slice
#' @export
vec_assign <- function(x, i, value, ..., x_arg = "", value_arg = "") {
check_dots_empty0(...)
.Call(ffi_assign, x, i, value, environment())
}
vec_assign_fallback <- function(x, i, value) {
# Work around bug in base `[<-`
existing <- !is.na(i)
i <- vec_slice(i, existing)
value <- vec_slice(value, existing)
d <- vec_dim_n(x)
miss_args <- rep(list(missing_arg()), d - 1)
eval_bare(expr(x[i, !!!miss_args] <- value))
x
}
# `start` is 0-based
vec_assign_seq <- function(x, value, start, size, increasing = TRUE) {
.Call(ffi_assign_seq, x, value, start, size, increasing)
}
vec_assign_params <- function(x, i, value, assign_names = FALSE) {
.Call(ffi_assign_params, x, i, value, assign_names)
}
vec_remove <- function(x, i) {
vec_slice(x, -vec_as_location(i, length(x), names(x)))
}
vec_index <- function(x, i, ...) {
i <- maybe_missing(i, TRUE)
out <- vec_slice(x, i)
if (!dots_n(...)) {
return(out)
}
# Need to unclass to avoid infinite recursion through `[`
proxy <- vec_data(out)
out <- proxy[, ..., drop = FALSE]
vec_restore(out, x)
}
#' Initialize a vector
#'
#' @param x Template of vector to initialize.
#' @param n Desired size of result.
#' @export
#' @section Dependencies:
#' * vec_slice()
#' @examples
#' vec_init(1:10, 3)
#' vec_init(Sys.Date(), 5)
#' vec_init(mtcars, 2)
vec_init <- function(x, n = 1L) {
.Call(ffi_init, x, n, environment())
}
# Exposed for testing (`start` is 0-based)
vec_slice_seq <- function(x, start, size, increasing = TRUE) {
.Call(ffi_slice_seq, x, start, size, increasing)
}
# Exposed for testing (`i` is 1-based)
vec_slice_rep <- function(x, i, n) {
.Call(ffi_slice_rep, x, i, n)
}
# Forwards arguments to `base::rep()`
base_vec_rep <- function(x, ...) {
i <- rep(seq_len(vec_size(x)), ...)
vec_slice(x, i)
}
# Emulates `length<-`
vec_size_assign <- function(x, n) {
x_size <- vec_size(x)
if (n > x_size) {
i <- seq_len(x_size)
i <- c(i, vec_init(int(), n - x_size))
} else {
i <- seq_len(n)
}
vec_slice(x, i)
}
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/slice.R
|
#' Split a vector into groups
#'
#' This is a generalisation of [split()] that can split by any type of vector,
#' not just factors. Instead of returning the keys in the character names,
#' the are returned in a separate parallel vector.
#'
#' @param x Vector to divide into groups.
#' @param by Vector whose unique values defines the groups.
#' @return A data frame with two columns and size equal to
#' `vec_size(vec_unique(by))`. The `key` column has the same type as
#' `by`, and the `val` column is a list containing elements of type
#' `vec_ptype(x)`.
#'
#' Note for complex types, the default `data.frame` print method will be
#' suboptimal, and you will want to coerce into a tibble to better
#' understand the output.
#' @export
#'
#' @section Dependencies:
#' - [vec_group_loc()]
#' - [vec_chop()]
#'
#' @examples
#' vec_split(mtcars$cyl, mtcars$vs)
#' vec_split(mtcars$cyl, mtcars[c("vs", "am")])
#'
#' if (require("tibble")) {
#' as_tibble(vec_split(mtcars$cyl, mtcars[c("vs", "am")]))
#' as_tibble(vec_split(mtcars, mtcars[c("vs", "am")]))
#' }
vec_split <- function(x, by) {
.Call(vctrs_split, x, by)
}
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/split.R
|
#' Create a vector of locations
#'
#' @description
#'
#' These helpers provide a means of standardizing common indexing
#' methods such as integer, character or logical indexing.
#'
#' * `vec_as_location()` accepts integer, character, or logical vectors
#' of any size. The output is always an integer vector that is
#' suitable for subsetting with `[` or [vec_slice()]. It might be a
#' different size than the input because negative selections are
#' transformed to positive ones and logical vectors are transformed
#' to a vector of indices for the `TRUE` locations.
#'
#' * `vec_as_location2()` accepts a single number or string. It returns
#' a single location as a integer vector of size 1. This is suitable
#' for extracting with `[[`.
#'
#' * `num_as_location()` and `num_as_location2()` are specialized variants
#' that have extra options for numeric indices.
#'
#' @inheritParams vec_slice
#' @inheritParams rlang::args_error_context
#'
#' @param n A single integer representing the total size of the
#' object that `i` is meant to index into.
#'
#' @param names If `i` is a character vector, `names` should be a character
#' vector that `i` will be matched against to construct the index. Otherwise,
#' not used. The default value of `NULL` will result in an error
#' if `i` is a character vector.
#'
#' @param missing How should missing `i` values be handled?
#' - `"error"` throws an error.
#' - `"propagate"` returns them as is.
#' - `"remove"` removes them.
#'
#' By default, vector subscripts propagate missing values but scalar
#' subscripts error on them.
#'
#' Propagated missing values can't be combined with negative indices when
#' `negative = "invert"`, because they can't be meaningfully inverted.
#'
#' @param arg The argument name to be displayed in error messages.
#'
#' @return
#' - `vec_as_location()` and `num_as_location()` return an integer vector that
#' can be used as an index in a subsetting operation.
#'
#' - `vec_as_location2()` and `num_as_location2()` return an integer of size 1
#' that can be used a scalar index for extracting an element.
#'
#' @examples
#' x <- array(1:6, c(2, 3))
#' dimnames(x) <- list(c("r1", "r2"), c("c1", "c2", "c3"))
#'
#' # The most common use case validates row indices
#' vec_as_location(1, vec_size(x))
#'
#' # Negative indices can be used to index from the back
#' vec_as_location(-1, vec_size(x))
#'
#' # Character vectors can be used if `names` are provided
#' vec_as_location("r2", vec_size(x), rownames(x))
#'
#' # You can also construct an index for dimensions other than the first
#' vec_as_location(c("c2", "c1"), ncol(x), colnames(x))
#'
#' @keywords internal
#' @export
vec_as_location <- function(i,
n,
names = NULL,
...,
missing = c("propagate", "remove", "error"),
arg = caller_arg(i),
call = caller_env()) {
check_dots_empty0(...)
.Call(
ffi_as_location,
i = i,
n = n,
names = names,
loc_negative = "invert",
loc_oob = "error",
loc_zero = "remove",
missing = missing,
frame = environment()
)
}
#' @rdname vec_as_location
#'
#' @param negative How should negative `i` values be handled?
#' - `"error"` throws an error.
#' - `"ignore"` returns them as is.
#' - `"invert"` returns the positive location generated by inverting the
#' negative location. When inverting, positive and negative locations
#' can't be mixed. This option is only applicable for `num_as_location()`.
#'
#' @param oob How should out-of-bounds `i` values be handled?
#' - `"error"` throws an error.
#' - `"remove"` removes both positive and negative out-of-bounds locations.
#' - `"extend"` allows positive out-of-bounds locations if they directly
#' follow the end of a vector. This can be used to implement extendable
#' vectors, like `letters[1:30]`.
#'
#' @param zero How should zero `i` values be handled?
#' - `"error"` throws an error.
#' - `"remove"` removes them.
#' - `"ignore"` returns them as is.
#'
#' @export
num_as_location <- function(i,
n,
...,
missing = c("propagate", "remove", "error"),
negative = c("invert", "error", "ignore"),
oob = c("error", "remove", "extend"),
zero = c("remove", "error", "ignore"),
arg = caller_arg(i),
call = caller_env()) {
check_dots_empty0(...)
if (is.object(i) || !(is_integer(i) || is_double(i))) {
abort("`i` must be a numeric vector.")
}
.Call(
ffi_as_location,
i = i,
n = n,
names = NULL,
loc_negative = negative,
loc_oob = oob,
loc_zero = zero,
missing = missing,
env = environment()
)
}
#' @rdname vec_as_location
#' @export
vec_as_location2 <- function(i,
n,
names = NULL,
...,
missing = c("error", "propagate"),
arg = caller_arg(i),
call = caller_env()) {
check_dots_empty0(...)
result_get(vec_as_location2_result(
i,
n = n,
names = names,
negative = "error",
missing = missing,
arg = arg,
call = call
))
}
#' @rdname vec_as_location
#' @export
num_as_location2 <- function(i,
n,
...,
negative = c("error", "ignore"),
missing = c("error", "propagate"),
arg = caller_arg(i),
call = caller_env()) {
check_dots_empty0(...)
if (!is_integer(i) && !is_double(i)) {
abort("`i` must be a numeric vector.", call = call)
}
result_get(vec_as_location2_result(
i,
n = n,
names = NULL,
negative = negative,
missing = missing,
arg = arg,
call = call
))
}
vec_as_location2_result <- function(i,
n,
names,
missing,
negative,
arg,
call) {
allow_missing <- arg_match0(missing, c("error", "propagate")) == "propagate"
allow_negative <- arg_match0(negative, c("error", "ignore")) == "ignore"
result <- vec_as_subscript2_result(
i = i,
arg = arg,
call = call
)
if (!is_null(result$err)) {
parent <- result$err
return(result(err = new_error_location2_type(
i = i,
subscript_arg = arg,
body = parent$body,
call = call
)))
}
# Locations must be size 1, can't be NA, and must be positive
i <- result$ok
if (length(i) != 1L) {
return(result(err = new_error_location2_type(
i = i,
subscript_arg = arg,
body = cnd_bullets_location2_need_scalar,
call = call
)))
}
neg <- typeof(i) == "integer" && !is.na(i) && i < 0L
if (allow_negative && neg) {
i <- -i
}
if (is.na(i)) {
if (!allow_missing && is.na(i)) {
result <- result(err = new_error_location2_type(
i = i,
subscript_arg = arg,
body = cnd_bullets_location2_need_present,
call = call
))
} else {
result <- result(i)
}
return(result)
}
if (identical(i, 0L)) {
return(result(err = new_error_location2_type(
i = i,
subscript_arg = arg,
body = cnd_bullets_location2_need_positive,
call = call
)))
}
if (!allow_negative && neg) {
return(result(err = new_error_location2_type(
i = i,
subscript_arg = arg,
body = cnd_bullets_location2_need_positive,
call = call
)))
}
err <- NULL
i <- tryCatch(
vec_as_location(i, n, names = names, arg = arg, call = call),
vctrs_error_subscript = function(err) {
err[["subscript_scalar"]] <- TRUE
err <<- err
i
}
)
if (!is_null(err)) {
return(result(err = err))
}
if (neg) {
i <- -i
}
result(i)
}
stop_location_negative_missing <- function(i, ..., call = caller_env()) {
cnd_signal(new_error_subscript_type(
i,
...,
body = cnd_body_vctrs_error_location_negative_missing,
call = call
))
}
cnd_body_vctrs_error_location_negative_missing <- function(cnd, ...) {
missing_loc <- which(is.na(cnd$i))
arg <- append_arg("Subscript", cnd$subscript_arg)
if (length(missing_loc) == 1) {
loc <- glue::glue("{arg} has a missing value at location {missing_loc}.")
} else {
n_loc <- length(missing_loc)
missing_loc <- ensure_full_stop(enumerate(missing_loc))
loc <- glue::glue(
"{arg} has {n_loc} missing values at locations {missing_loc}"
)
}
format_error_bullets(c(
x = "Negative locations can't have missing values.",
i = loc
))
}
stop_location_negative_positive <- function(i, ..., call = caller_env()) {
cnd_signal(new_error_subscript_type(
i,
...,
body = cnd_body_vctrs_error_location_negative_positive,
call = call
))
}
cnd_body_vctrs_error_location_negative_positive <- function(cnd, ...) {
positive_loc <- which(cnd$i > 0)
arg <- append_arg("Subscript", cnd$subscript_arg)
if (length(positive_loc) == 1) {
loc <- glue::glue("{arg} has a positive value at location {positive_loc}.")
} else {
n_loc <- length(positive_loc)
positive_loc <- ensure_full_stop(enumerate(positive_loc))
loc <- glue::glue(
"{arg} has {n_loc} positive values at locations {positive_loc}"
)
}
format_error_bullets(c(
x = "Negative and positive locations can't be mixed.",
i = loc
))
}
new_error_location2_type <- function(i,
...,
class = NULL) {
new_error_subscript2_type(
class = class,
i = i,
numeric = "cast",
character = "cast",
...
)
}
cnd_bullets_location2_need_scalar <- function(cnd, ...) {
cnd$subscript_arg <- append_arg("Subscript", cnd$subscript_arg)
format_error_bullets(c(
x = glue::glue_data(cnd, "{subscript_arg} must be size 1, not {length(i)}.")
))
}
cnd_bullets_location2_need_present <- function(cnd, ...) {
cnd$subscript_arg <- append_arg("Subscript", cnd$subscript_arg)
format_error_bullets(c(
x = glue::glue_data(cnd, "{subscript_arg} must be a location, not {obj_type_friendly(i)}.")
))
}
cnd_bullets_location2_need_positive <- function(cnd, ...) {
cnd$subscript_arg <- append_arg("Subscript", cnd$subscript_arg)
format_error_bullets(c(
x = glue::glue_data(cnd, "{subscript_arg} must be a positive location, not {i}.")
))
}
stop_location_negative <- function(i, ..., call = caller_env()) {
cnd_signal(new_error_subscript_type(
i,
body = cnd_bullets_location_need_non_negative,
...,
call = call
))
}
cnd_bullets_location_need_non_negative <- function(cnd, ...) {
cnd$subscript_arg <- append_arg("Subscript", cnd$subscript_arg)
format_error_bullets(c(
x = glue::glue_data(cnd, "{subscript_arg} can't contain negative locations.")
))
}
stop_location_zero <- function(i, ..., call = caller_env()) {
cnd_signal(new_error_subscript_type(
i,
body = cnd_bullets_location_need_non_zero,
...,
call = call
))
}
cnd_bullets_location_need_non_zero <- function(cnd, ...) {
zero_loc <- which(cnd$i == 0)
zero_loc_size <- length(zero_loc)
arg <- append_arg("Subscript", cnd$subscript_arg)
if (zero_loc_size == 1) {
loc <- glue::glue("It has a `0` value at location {zero_loc}.")
} else {
zero_loc <- ensure_full_stop(enumerate(zero_loc))
loc <- glue::glue(
"It has {zero_loc_size} `0` values at locations {zero_loc}"
)
}
format_error_bullets(c(
x = glue::glue("{arg} can't contain `0` values."),
i = loc
))
}
stop_subscript_missing <- function(i, ..., call = caller_env()) {
cnd_signal(new_error_subscript_type(
i = i,
body = cnd_bullets_subscript_missing,
...,
call = call
))
}
cnd_bullets_subscript_missing <- function(cnd, ...) {
cnd$subscript_arg <- append_arg("Subscript", cnd$subscript_arg)
missing_loc <- which(is.na(cnd$i))
if (length(missing_loc) == 1) {
missing_line <- glue::glue("It has a missing value at location {missing_loc}.")
} else {
missing_enum <- ensure_full_stop(enumerate(missing_loc))
missing_line <- glue::glue("It has missing values at locations {missing_enum}")
}
format_error_bullets(c(
x = glue::glue_data(cnd, "{subscript_arg} can't contain missing values."),
x = missing_line
))
}
stop_subscript_empty <- function(i, ..., call = caller_env()) {
cnd_signal(new_error_subscript_type(
i = i,
body = cnd_bullets_subscript_empty,
...,
call = call
))
}
cnd_bullets_subscript_empty <- function(cnd, ...) {
cnd$subscript_arg <- append_arg("Subscript", cnd$subscript_arg)
loc <- which(cnd$i == "")
if (length(loc) == 1) {
line <- glue::glue("It has an empty string at location {loc}.")
} else {
enum <- ensure_full_stop(enumerate(loc))
line <- glue::glue("It has an empty string at locations {enum}")
}
format_error_bullets(c(
x = glue::glue_data(cnd, "{subscript_arg} can't contain the empty string."),
x = line
))
}
stop_indicator_size <- function(i, n, ..., call = caller_env()) {
cnd_signal(new_error_subscript_size(
i,
n = n,
...,
body = cnd_body_vctrs_error_indicator_size,
call = call
))
}
cnd_body_vctrs_error_indicator_size <- function(cnd, ...) {
cnd$subscript_arg <- append_arg("Logical subscript", cnd$subscript_arg)
glue_data_bullets(
cnd,
x = "{subscript_arg} must be size 1 or {n}, not {vec_size(i)}."
)
}
stop_subscript_oob <- function(i,
subscript_type,
...,
call = caller_env()) {
stop_subscript(
class = "vctrs_error_subscript_oob",
i = i,
subscript_type = subscript_type,
...,
call = call
)
}
#' @export
cnd_header.vctrs_error_subscript_oob <- function(cnd, ...) {
if (cnd_subscript_oob_non_consecutive(cnd)) {
return(cnd_header_vctrs_error_subscript_oob_non_consecutive(cnd, ...))
}
elt <- cnd_subscript_element(cnd)
action <- cnd_subscript_action(cnd)
type <- cnd_subscript_type(cnd)
if (action %in% c("rename", "relocate") || type == "character") {
glue::glue("Can't {action} {elt[[2]]} that don't exist.")
} else {
glue::glue("Can't {action} {elt[[2]]} past the end.")
}
}
#' @export
cnd_body.vctrs_error_subscript_oob <- function(cnd, ...) {
switch(cnd_subscript_type(cnd),
numeric =
if (cnd_subscript_oob_non_consecutive(cnd)) {
cnd_body_vctrs_error_subscript_oob_non_consecutive(cnd, ...)
} else {
cnd_body_vctrs_error_subscript_oob_location(cnd, ...)
},
character =
cnd_body_vctrs_error_subscript_oob_name(cnd, ...),
abort("Internal error: subscript type can't be `logical` for OOB errors.")
)
}
cnd_body_vctrs_error_subscript_oob_location <- function(cnd, ...) {
i <- cnd$i
# In case of missing locations
i <- i[!is.na(i)]
if (cnd_subscript_action(cnd) == "negate") {
# Only report negative indices
i <- i[i < 0L]
}
# In case of negative indexing
i <- abs(i)
oob <- i[i > cnd$size]
oob_enum <- vctrs_cli_vec(oob)
n_loc <- length(oob)
n <- cnd$size
elt <- cnd_subscript_element_cli(n, cnd)
# TODO: Switch to `format_inline()` and format bullets lazily through rlang
cli::format_error(c(
"i" = "{cli::qty(n_loc)} Location{?s} {oob_enum} do{?esn't/n't} exist.",
"i" = "There {cli::qty(n)} {?is/are} only {elt}."
))
}
cnd_body_vctrs_error_subscript_oob_name <- function(cnd, ...) {
elt <- cnd_subscript_element(cnd, capital = TRUE)
oob <- cnd$i[!cnd$i %in% cnd$names]
oob_enum <- enumerate(glue::backtick(oob))
format_error_bullets(c(
x = glue::glue(ngettext(
length(oob),
"{elt[[1]]} {oob_enum} doesn't exist.",
"{elt[[2]]} {oob_enum} don't exist."
))
))
}
vctrs_cli_vec <- function(x, ..., vec_trunc = 5) {
cli::cli_vec(as.character(x), list(..., vec_trunc = vec_trunc))
}
stop_location_oob_non_consecutive <- function(i,
size,
...,
call = caller_env()) {
stop_subscript_oob(
i = i,
size = size,
subscript_type = "numeric",
subscript_oob_non_consecutive = TRUE,
...,
call = call
)
}
cnd_header_vctrs_error_subscript_oob_non_consecutive <- function(cnd, ...) {
action <- cnd_subscript_action(cnd)
elt <- cnd_subscript_element(cnd)
glue::glue("Can't {action} {elt[[2]]} beyond the end with non-consecutive locations.")
}
cnd_body_vctrs_error_subscript_oob_non_consecutive <- function(cnd, ...) {
i <- sort(cnd$i)
i <- i[i > cnd$size]
non_consecutive <- i[c(TRUE, diff(i) != 1L)]
arg <- append_arg("Subscript", cnd$subscript_arg)
if (length(non_consecutive) == 1) {
x_line <- glue::glue("{arg} contains non-consecutive location {non_consecutive}.")
} else {
non_consecutive <- ensure_full_stop(enumerate(non_consecutive))
x_line <- glue::glue("{arg} contains non-consecutive locations {non_consecutive}")
}
glue_data_bullets(
cnd,
i = "Input has size {size}.",
x = x_line
)
}
cnd_subscript_oob_non_consecutive <- function(cnd) {
out <- cnd$subscript_oob_non_consecutive %||% FALSE
check_bool(out)
out
}
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/subscript-loc.R
|
#' Convert to a base subscript type
#'
#' @description
#'
#' `r lifecycle::badge("experimental")`
#'
#' Convert `i` to the base type expected by [vec_as_location()] or
#' [vec_as_location2()]. The values of the subscript type are
#' not checked in any way (length, missingness, negative elements).
#'
#' @inheritParams vec_as_location
#'
#' @param logical,numeric,character How to handle logical, numeric,
#' and character subscripts.
#'
#' If `"cast"` and the subscript is not one of the three base types
#' (logical, integer or character), the subscript is
#' [cast][vec_cast] to the relevant base type, e.g. factors are
#' coerced to character. `NULL` is treated as an empty integer
#' vector, and is thus coercible depending on the setting of
#' `numeric`. Symbols are treated as character vectors and thus
#' coercible depending on the setting of `character`.
#'
#' If `"error"`, the subscript type is disallowed and triggers an
#' informative error.
#' @keywords internal
#' @export
vec_as_subscript <- function(i,
...,
logical = c("cast", "error"),
numeric = c("cast", "error"),
character = c("cast", "error"),
arg = NULL,
call = caller_env()) {
check_dots_empty0(...)
.Call(
ffi_as_subscript,
i = i,
logical = logical,
numeric = numeric,
character = character,
frame = environment()
)
}
vec_as_subscript_result <- function(i,
arg,
call,
logical,
numeric,
character) {
.Call(
ffi_as_subscript_result,
i = i,
logical = logical,
numeric = numeric,
character = character,
frame = environment()
)
}
#' @rdname vec_as_subscript
#' @export
vec_as_subscript2 <- function(i,
...,
numeric = c("cast", "error"),
character = c("cast", "error"),
arg = NULL,
call = caller_env()) {
check_dots <- function(..., logical = "error", call = caller_env()) {
if (!is_string(logical, "error")) {
abort(
"`vctrs::vec_as_subscript2(logical = 'cast')` is deprecated.",
call = caller_env()
)
}
check_dots_empty0(..., call = call)
}
check_dots(...)
result_get(vec_as_subscript2_result(
i,
arg,
call,
numeric = numeric,
character = character
))
}
vec_as_subscript2_result <- function(i,
arg,
call,
numeric = "cast",
character = "cast") {
numeric <- arg_match0(numeric, c("cast", "error"))
character <- arg_match0(character, c("cast", "error"))
result <- vec_as_subscript_result(
i,
arg = arg,
call = call,
logical = "error",
numeric = numeric,
character = character
)
# This should normally be a `vctrs_error_subscript`. Indicate to
# message methods that this error refers to a `[[` subscript.
if (!is_null(result$err)) {
result$err$subscript_scalar <- TRUE
}
result
}
subscript_type_opts <- c("logical", "numeric", "character")
subscript_type_opts_indefinite_singular <- c("a logical flag", "a location", "a name")
subscript_type_opts_indefinite_plural <- c("logical flags", "locations", "names")
as_opts_subscript_type <- function(x, arg = NULL) {
if (inherits(x, "vctrs_opts_subscript_type")) {
return(x)
}
new_opts(
x,
subscript_type_opts,
subclass = "vctrs_opts_subscript_type",
arg = arg
)
}
as_opts_subscript2_type <- function(x, arg = NULL) {
if ("logical" %in% x) {
abort("Logical subscripts can't be converted to a single location.")
}
as_opts_subscript_type(x, arg = arg)
}
stop_subscript <- function(i,
...,
class = NULL,
call = caller_env()) {
abort(
class = c(class, "vctrs_error_subscript"),
i = i,
...,
call = call
)
}
new_error_subscript <- function(class = NULL, i, ...) {
error_cnd(
c(class, "vctrs_error_subscript"),
i = i,
...
)
}
new_error_subscript_type <- function(i,
logical = "cast",
numeric = "cast",
character = "cast",
...,
call = NULL,
class = NULL) {
new_error_subscript(
class = c(class, "vctrs_error_subscript_type"),
i = i,
logical = logical,
numeric = numeric,
character = character,
...,
call = call
)
}
#' @export
cnd_header.vctrs_error_subscript_type <- function(cnd, ...) {
arg <- cnd[["subscript_arg"]]
if (is_subscript_arg(arg)) {
with <- glue::glue(" with {format_subscript_arg(arg)}")
} else {
with <- ""
}
action <- cnd_subscript_action(cnd, assign_to = FALSE)
elt <- cnd_subscript_element(cnd)
if (cnd_subscript_scalar(cnd)) {
glue::glue("Can't {action} {elt[[1]]}{with}.")
} else {
glue::glue("Can't {action} {elt[[2]]}{with}.")
}
}
#' @export
cnd_body.vctrs_error_subscript_type <- function(cnd, ...) {
arg <- cnd_subscript_arg(cnd)
type <- obj_type_friendly(cnd$i)
expected_types <- cnd_subscript_expected_types(cnd)
format_error_bullets(c(
x = cli::format_inline("{arg} must be {.or {expected_types}}, not {type}.")
))
}
new_cnd_bullets_subscript_lossy_cast <- function(lossy_err) {
function(cnd, ...) {
format_error_bullets(c(x = cnd_header(lossy_err)))
}
}
collapse_subscript_type <- function(cnd) {
types <- cnd_subscript_expected_types(cnd)
if (length(types) == 2) {
last <- " or "
} else {
last <- ", or "
}
glue::glue_collapse(types, sep = ", ", last = last)
}
cnd_subscript_expected_types <- function(cnd) {
types <- c("logical", "numeric", "character")
allowed <- cnd[types] != "error"
types[allowed]
}
new_error_subscript_size <- function(i,
...,
class = NULL) {
new_error_subscript(
class = c(class, "vctrs_error_subscript_size"),
i = i,
...
)
}
#' @export
cnd_header.vctrs_error_subscript_size <- function(cnd, ...) {
cnd_header.vctrs_error_subscript_type(cnd, ...)
}
new_error_subscript2_type <- function(i,
numeric,
character,
...) {
new_error_subscript_type(
i = i,
logical = "error",
numeric = numeric,
character = character,
subscript_scalar = TRUE,
...
)
}
cnd_body_subscript_dim <- function(cnd, ...) {
arg <- append_arg("Subscript", cnd$subscript_arg)
dim <- length(dim(cnd$i))
if (dim < 2) {
abort("Internal error: Unexpected dimensionality in `cnd_body_subcript_dim()`.")
}
if (dim == 2) {
shape <- "a matrix"
} else {
shape <- "an array"
}
format_error_bullets(c(
x = glue::glue("{arg} must be a simple vector, not {shape}.")
))
}
cnd_subscript_element <- function(cnd, capital = FALSE) {
elt <- cnd$subscript_elt %||% "element"
if (!is_string(elt, c("element", "row", "column", "table"))) {
abort(paste0(
"Internal error: `cnd$subscript_elt` must be one of ",
"`element`, `row`, `column` or `table`."
))
}
if (capital) {
switch(
elt,
element = c("Element", "Elements"),
row = c("Row", "Rows"),
column = c("Column", "Columns"),
table = c("Table", "Tables")
)
} else {
switch(elt,
element = c("element", "elements"),
row = c("row", "rows"),
column = c("column", "columns"),
table = c("table", "tables")
)
}
}
cnd_subscript_element_cli <- function(n, cnd, capital = FALSE) {
elt <- cnd$subscript_elt %||% "element"
if (!is_string(elt, c("element", "row", "column", "table"))) {
abort(paste0(
"Internal error: `cnd$subscript_elt` must be one of ",
"`element`, `row`, `column` or `table`."
))
}
if (capital) {
elt <- switch(
elt,
element = "Element{?s}",
row = "Row{?s}",
column = "Column{?s}",
table = "Table{?s}"
)
} else {
elt <- switch(
elt,
element = "element{?s}",
row = "row{?s}",
column = "column{?s}",
table = "table{?s}"
)
}
cli::pluralize("{n} ", elt)
}
subscript_actions <- c(
"select", "subset", "extract",
"assign", "rename", "relocate",
"remove", "negate"
)
cnd_subscript_action <- function(cnd, assign_to = TRUE) {
action <- cnd$subscript_action
if (is_null(action)) {
if (cnd_subscript_scalar(cnd)) {
action <- "extract"
} else {
action <- "subset"
}
}
if (!is_string(action, subscript_actions)) {
cli::cli_abort(
"`cnd$subscript_action` must be one of {.or {.arg {subscript_actions}}}.",
.internal = TRUE
)
}
if (assign_to && action == "assign") {
"assign to"
} else {
action
}
}
cnd_subscript_arg <- function(cnd, ...) {
format_subscript_arg(cnd[["subscript_arg"]], ...)
}
format_subscript_arg <- function(arg, capitalise = TRUE) {
if (is_subscript_arg(arg)) {
if (!is_string(arg)) {
arg <- as_label(arg)
}
cli::format_inline("{.arg {arg}}")
} else {
if (capitalise) {
"Subscript"
} else {
"subscript"
}
}
}
is_subscript_arg <- function(x) {
!is_null(x) && !is_string(x, "")
}
cnd_subscript_type <- function(cnd) {
type <- cnd$subscript_type
if (!is_string(type, c("logical", "numeric", "character"))) {
abort("Internal error: `cnd$subscript_type` must be `logical`, `numeric`, or `character`.")
}
type
}
cnd_subscript_scalar <- function(cnd) {
out <- cnd$subscript_scalar %||% FALSE
if (!is_bool(out)) {
abort("Internal error: `cnd$subscript_scalar` must be a boolean.")
}
out
}
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/subscript.R
|
vec_normalize_encoding <- function(x) {
.Call(vctrs_normalize_encoding, x)
}
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/translate.R
|
#' AsIs S3 class
#'
#' These functions help the base AsIs class fit into the vctrs type system
#' by providing coercion and casting functions.
#'
#' @keywords internal
#' @name as-is
NULL
# ------------------------------------------------------------------------------
# Printing
#' @export
vec_ptype_full.AsIs <- function(x, ...) {
x <- asis_strip(x)
paste0("I<", vec_ptype_full(x), ">")
}
#' @export
vec_ptype_abbr.AsIs <- function(x, ...) {
x <- asis_strip(x)
paste0("I<", vec_ptype_abbr(x), ">")
}
# ------------------------------------------------------------------------------
# Proxy / restore
# Arises with base df ctor: `data.frame(x = I(list(1, 2:3)))`
#' @export
vec_proxy.AsIs <- function(x, ...) {
x <- asis_strip(x)
vec_proxy(x)
}
#' @export
vec_restore.AsIs <- function(x, to, ...) {
asis_restore(x)
}
#' @export
vec_proxy_equal.AsIs <- function(x, ...) {
x <- asis_strip(x)
vec_proxy_equal(x)
}
#' @export
vec_proxy_compare.AsIs <- function(x, ...) {
x <- asis_strip(x)
vec_proxy_compare(x)
}
#' @export
vec_proxy_order.AsIs <- function(x, ...) {
x <- asis_strip(x)
vec_proxy_order(x)
}
# ------------------------------------------------------------------------------
# Coercion
#' @rdname as-is
#' @export vec_ptype2.AsIs
#' @method vec_ptype2 AsIs
#' @export
vec_ptype2.AsIs <- function(x, y, ..., x_arg = "", y_arg = "") {
UseMethod("vec_ptype2.AsIs")
}
#' @method vec_ptype2.AsIs AsIs
#' @export
vec_ptype2.AsIs.AsIs <- function(x, y, ..., x_arg = "", y_arg = "") {
x <- asis_strip(x)
y <- asis_strip(y)
vec_ptype2_asis(x, y, ..., x_arg = x_arg, y_arg = y_arg)
}
vec_ptype2_asis_left <- function(x, y, ...) {
x <- asis_strip(x)
vec_ptype2_asis(x, y, ...)
}
vec_ptype2_asis_right <- function(x, y, ...) {
y <- asis_strip(y)
vec_ptype2_asis(x, y, ...)
}
vec_ptype2_asis <- function(x, y, ...) {
out <- vec_ptype2(x, y, ...)
asis_restore(out)
}
# ------------------------------------------------------------------------------
# Casting
vec_cast_from_asis <- function(x, to, ..., call = caller_env()) {
x <- asis_strip(x)
vec_cast(x, to, ..., call = call)
}
vec_cast_to_asis <- function(x, to, ..., call = caller_env()) {
to <- asis_strip(to)
out <- vec_cast(x, to, ..., call = call)
asis_restore(out)
}
# ------------------------------------------------------------------------------
is_asis <- function(x) {
inherits(x, "AsIs")
}
asis_strip <- function(x) {
class(x) <- setdiff(class(x), "AsIs")
x
}
asis_restore <- function(x) {
# Using `oldClass()` here to return `NULL` for atomics
# so that their implicit class isn't added
class(x) <- c("AsIs", oldClass(x))
x
}
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/type-asis.R
|
# Type2 -------------------------------------------------------------------
# Left generics -----------------------------------------------------------
#' @rdname vec_ptype2
#' @export vec_ptype2.logical
#' @method vec_ptype2 logical
#' @export
vec_ptype2.logical <- function(x, y, ..., x_arg = "", y_arg = "") {
UseMethod("vec_ptype2.logical")
}
#' @rdname vec_ptype2
#' @export vec_ptype2.integer
#' @method vec_ptype2 integer
#' @export
vec_ptype2.integer <- function(x, y, ..., x_arg = "", y_arg = "") {
UseMethod("vec_ptype2.integer")
}
#' @rdname vec_ptype2
#' @export vec_ptype2.double
#' @method vec_ptype2 double
#' @export
vec_ptype2.double <- function(x, y, ..., x_arg = "", y_arg = "") {
UseMethod("vec_ptype2.double")
}
#' @rdname vec_ptype2
#' @export vec_ptype2.complex
#' @method vec_ptype2 complex
#' @export
vec_ptype2.complex <- function(x, y, ..., x_arg = "", y_arg = "") {
UseMethod("vec_ptype2.complex")
}
#' @rdname vec_ptype2
#' @export vec_ptype2.character
#' @method vec_ptype2 character
#' @export
vec_ptype2.character <- function(x, y, ..., x_arg = "", y_arg = "") {
UseMethod("vec_ptype2.character")
}
#' @rdname vec_ptype2
#' @export vec_ptype2.raw
#' @method vec_ptype2 raw
#' @export
vec_ptype2.raw <- function(x, y, ..., x_arg = "", y_arg = "") {
UseMethod("vec_ptype2.raw")
}
#' @rdname vec_ptype2
#' @export vec_ptype2.list
#' @method vec_ptype2 list
#' @export
vec_ptype2.list <- function(x, y, ..., x_arg = "", y_arg = "") {
UseMethod("vec_ptype2.list")
}
# Numeric-ish
#' @method vec_ptype2.logical logical
#' @export
vec_ptype2.logical.logical <- function(x, y, ..., x_arg = "", y_arg = "") {
stop_native_implementation("vec_ptype2.logical.logical")
}
#' @export
#' @method vec_ptype2.integer integer
vec_ptype2.integer.integer <- function(x, y, ..., x_arg = "", y_arg = "") {
stop_native_implementation("vec_ptype2.integer.integer")
}
#' @export
#' @method vec_ptype2.logical integer
vec_ptype2.logical.integer <- function(x, y, ..., x_arg = "", y_arg = "") {
stop_native_implementation("vec_ptype2.logical.integer")
}
#' @export
#' @method vec_ptype2.integer logical
vec_ptype2.integer.logical <- function(x, y, ..., x_arg = "", y_arg = "") {
stop_native_implementation("vec_ptype2.integer.logical")
}
#' @export
#' @method vec_ptype2.double double
vec_ptype2.double.double <- function(x, y, ..., x_arg = "", y_arg = "") {
stop_native_implementation("vec_ptype2.double.double")
}
#' @export
#' @method vec_ptype2.logical double
vec_ptype2.logical.double <- function(x, y, ..., x_arg = "", y_arg = "") {
stop_native_implementation("vec_ptype2.logical.double")
}
#' @export
#' @method vec_ptype2.double logical
vec_ptype2.double.logical <- function(x, y, ..., x_arg = "", y_arg = "") {
stop_native_implementation("vec_ptype2.double.logical")
}
#' @export
#' @method vec_ptype2.integer double
vec_ptype2.integer.double <- function(x, y, ..., x_arg = "", y_arg = "") {
stop_native_implementation("vec_ptype2.integer.double")
}
#' @export
#' @method vec_ptype2.double integer
vec_ptype2.double.integer <- function(x, y, ..., x_arg = "", y_arg = "") {
stop_native_implementation("vec_ptype2.double.integer")
}
#' @export
#' @method vec_ptype2.complex complex
vec_ptype2.complex.complex <- function(x, y, ..., x_arg = "", y_arg = "") {
stop_native_implementation("vec_ptype2.complex.complex")
}
#' @export
#' @method vec_ptype2.integer complex
vec_ptype2.integer.complex <- function(x, y, ..., x_arg = "", y_arg = "") {
stop_native_implementation("vec_ptype2.integer.complex")
}
#' @export
#' @method vec_ptype2.complex integer
vec_ptype2.complex.integer <- function(x, y, ..., x_arg = "", y_arg = "") {
stop_native_implementation("vec_ptype2.complex.integer")
}
#' @export
#' @method vec_ptype2.double complex
vec_ptype2.double.complex <- function(x, y, ..., x_arg = "", y_arg = "") {
stop_native_implementation("vec_ptype2.double.complex")
}
#' @export
#' @method vec_ptype2.complex double
vec_ptype2.complex.double <- function(x, y, ..., x_arg = "", y_arg = "") {
stop_native_implementation("vec_ptype2.complex.double")
}
# Character
#' @method vec_ptype2.character character
#' @export
vec_ptype2.character.character <- function(x, y, ..., x_arg = "", y_arg = "") {
stop_native_implementation("vec_ptype2.character.character")
}
# Raw
#' @export
#' @method vec_ptype2.raw raw
vec_ptype2.raw.raw <- function(x, y, ..., x_arg = "", y_arg = "") {
stop_native_implementation("vec_ptype2.raw.raw")
}
# Lists
#' @method vec_ptype2.list list
#' @export
vec_ptype2.list.list <- function(x, y, ..., x_arg = "", y_arg = "") {
stop_native_implementation("vec_ptype2.list.list")
}
# Cast --------------------------------------------------------------------
# These methods for base types are handled at the C level unless
# inputs have shape or have lossy casts
#' @export
#' @rdname vec_cast
#' @export vec_cast.logical
#' @method vec_cast logical
vec_cast.logical <- function(x, to, ...) {
UseMethod("vec_cast.logical")
}
#' @export
#' @method vec_cast.logical logical
vec_cast.logical.logical <- function(x, to, ...) {
shape_broadcast(x, to, ...)
}
#' @export
#' @method vec_cast.logical integer
vec_cast.logical.integer <- function(x,
to,
...,
x_arg = "",
to_arg = "",
call = caller_env()) {
out <- vec_coerce_bare(x, "logical")
out <- shape_broadcast(
out,
to,
x_arg = x_arg,
to_arg = to_arg,
call = call
)
lossy <- !x %in% c(0L, 1L, NA_integer_)
maybe_lossy_cast(
out,
x,
to,
lossy,
x_arg = x_arg,
to_arg = to_arg,
call = call
)
}
#' @export
#' @method vec_cast.logical double
vec_cast.logical.double <- function(x,
to,
...,
x_arg = "",
to_arg = "",
call = caller_env()) {
out <- vec_coerce_bare(x, "logical")
out <- shape_broadcast(
out,
to,
x_arg = x_arg,
to_arg = to_arg,
call = call
)
lossy <- !x %in% c(0, 1, NA_real_)
maybe_lossy_cast(
out,
x,
to,
lossy,
x_arg = x_arg,
to_arg = to_arg,
call = call
)
}
#' @export
#' @rdname vec_cast
#' @export vec_cast.integer
#' @method vec_cast integer
vec_cast.integer <- function(x, to, ...) {
UseMethod("vec_cast.integer")
}
#' @export
#' @method vec_cast.integer logical
vec_cast.integer.logical <- function(x, to, ...) {
x <- vec_coerce_bare(x, "integer")
shape_broadcast(x, to, ...)
}
#' @export
#' @method vec_cast.integer integer
vec_cast.integer.integer <- function(x, to, ...) {
shape_broadcast(x, to, ...)
}
#' @export
#' @method vec_cast.integer double
vec_cast.integer.double <- function(x,
to,
...,
x_arg = "",
to_arg = "",
call = caller_env()) {
out <- suppressWarnings(vec_coerce_bare(x, "integer"))
x_na <- is.na(x)
lossy <- (out != x & !x_na) | xor(x_na, is.na(out))
out <- shape_broadcast(
out,
to,
x_arg = x_arg,
to_arg = to_arg,
call = call
)
maybe_lossy_cast(
out,
x,
to,
lossy,
x_arg = x_arg,
to_arg = to_arg,
call = call
)
}
#' @export
#' @rdname vec_cast
#' @export vec_cast.double
#' @method vec_cast double
vec_cast.double <- function(x, to, ...) {
UseMethod("vec_cast.double")
}
#' @export
#' @method vec_cast.double logical
vec_cast.double.logical <- function(x, to, ...) {
x <- vec_coerce_bare(x, "double")
shape_broadcast(x, to, ...)
}
#' @export
#' @method vec_cast.double integer
vec_cast.double.integer <- vec_cast.double.logical
#' @export
#' @method vec_cast.double double
vec_cast.double.double <- function(x, to, ...) {
shape_broadcast(x, to, ...)
}
#' @export
#' @rdname vec_cast
#' @export vec_cast.complex
#' @method vec_cast complex
vec_cast.complex <- function(x, to, ...) {
UseMethod("vec_cast.complex")
}
#' @export
#' @method vec_cast.complex logical
vec_cast.complex.logical <- function(x, to, ...) {
x <- vec_coerce_bare(x, "complex")
shape_broadcast(x, to, ...)
}
#' @export
#' @method vec_cast.complex integer
vec_cast.complex.integer <- vec_cast.complex.logical
#' @export
#' @method vec_cast.complex double
vec_cast.complex.double <- vec_cast.complex.logical
#' @export
#' @method vec_cast.complex complex
vec_cast.complex.complex <- function(x, to, ...) {
shape_broadcast(x, to, ...)
}
#' @export
#' @rdname vec_cast
#' @export vec_cast.raw
#' @method vec_cast raw
vec_cast.raw <- function(x, to, ...) {
UseMethod("vec_cast.raw")
}
#' @export
#' @method vec_cast.raw raw
vec_cast.raw.raw <- function(x, to, ...) {
shape_broadcast(x, to, ...)
}
#' @export
#' @rdname vec_cast
#' @export vec_cast.character
#' @method vec_cast character
vec_cast.character <- function(x, to, ...) {
UseMethod("vec_cast.character")
}
#' @export
#' @method vec_cast.character character
vec_cast.character.character <- function(x, to, ...) {
shape_broadcast(x, to, ...)
}
#' @rdname vec_cast
#' @export vec_cast.list
#' @method vec_cast list
#' @export
vec_cast.list <- function(x, to, ...) {
UseMethod("vec_cast.list")
}
#' @export
#' @method vec_cast.list list
vec_cast.list.list <- function(x, to, ...) {
shape_broadcast(x, to, ...)
}
# equal --------------------------------------------------------------
#' @export
vec_proxy_equal.array <- function(x, ...) {
# The conversion to data frame is only a stopgap, in the long
# term, we'll hash arrays natively. Note that hashing functions
# similarly convert to data frames.
x <- as.data.frame(x)
vec_proxy_equal(x)
}
# compare ------------------------------------------------------------
#' @export
vec_proxy_compare.raw <- function(x, ...) {
# because:
# order(as.raw(1:3))
# #> Error in order(as.raw(1:3)): unimplemented type 'raw' in 'orderVector1'
as.integer(x)
}
#' @export
vec_proxy_compare.list <- function(x, ...) {
stop_unsupported(x, "vec_proxy_compare")
}
#' @export
vec_proxy_compare.array <- function(x, ...) {
# The conversion to data frame is only a stopgap, in the long
# term, we'll hash arrays natively. Note that hashing functions
# similarly convert to data frames.
x <- as.data.frame(x)
vec_proxy_compare(x)
}
# order ------------------------------------------------------------
#' @export
vec_proxy_order.raw <- function(x, ...) {
# Can't rely on fallthrough behavior to `vec_proxy_compare()` because this
# isn't an S3 object. Have to call it manually.
vec_proxy_compare(x)
}
#' @export
vec_proxy_order.list <- function(x, ...) {
# Order lists by first appearance.
# This allows list elements to be grouped in `vec_order()`.
# Have to separately ensure missing values are propagated.
out <- vec_duplicate_id(x)
if (vec_any_missing(x)) {
missing <- vec_detect_missing(x)
out <- vec_assign(out, missing, NA_integer_)
}
out
}
#' @export
vec_proxy_order.array <- function(x, ...) {
# The conversion to data frame is only a stopgap, in the long
# term, we'll hash arrays natively. Note that hashing functions
# similarly convert to data frames.
x <- as.data.frame(x)
vec_proxy_order(x)
}
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/type-bare.R
|
#' Assemble attributes for data frame construction
#'
#' `new_data_frame()` constructs a new data frame from an existing list. It is
#' meant to be performant, and does not check the inputs for correctness in any
#' way. It is only safe to use after a call to [df_list()], which collects and
#' validates the columns used to construct the data frame.
#'
#' @seealso
#' [df_list()] for a way to safely construct a data frame's underlying
#' data structure from individual columns. This can be used to create a
#' named list for further use by `new_data_frame()`.
#'
#' @param x A named list of equal-length vectors. The lengths are not
#' checked; it is responsibility of the caller to make sure they are
#' equal.
#' @param n Number of rows. If `NULL`, will be computed from the length of
#' the first element of `x`.
#' @param ...,class Additional arguments for creating subclasses.
#'
#' The following attributes have special behavior:
#' - `"names"` is preferred if provided, overriding existing names in `x`.
#' - `"row.names"` is preferred if provided, overriding both `n` and the size
#' implied by `x`.
#'
#' @export
#' @examples
#' new_data_frame(list(x = 1:10, y = 10:1))
new_data_frame <- function(x = list(), n = NULL, ..., class = NULL) {
.External(ffi_new_data_frame, x, n, class, ...)
}
new_data_frame <- fn_inline_formals(new_data_frame, "x")
#' Collect columns for data frame construction
#'
#' `df_list()` constructs the data structure underlying a data
#' frame, a named list of equal-length vectors. It is often used in
#' combination with [new_data_frame()] to safely and consistently create
#' a helper function for data frame subclasses.
#'
#' @section Properties:
#'
#' - Inputs are [recycled][theory-faq-recycling] to a common size with
#' [vec_recycle_common()].
#'
#' - With the exception of data frames, inputs are not modified in any way.
#' Character vectors are never converted to factors, and lists are stored
#' as-is for easy creation of list-columns.
#'
#' - Unnamed data frame inputs are automatically unpacked. Named data frame
#' inputs are stored unmodified as data frame columns.
#'
#' - `NULL` inputs are completely ignored.
#'
#' - The dots are dynamic, allowing for splicing of lists with `!!!` and
#' unquoting.
#'
#' @seealso
#' [new_data_frame()] for constructing data frame subclasses from a validated
#' input. [data_frame()] for a fast data frame creation helper.
#'
#' @inheritParams rlang::args_error_context
#'
#' @param ... Vectors of equal-length. When inputs are named, those names
#' are used for names of the resulting list.
#' @param .size The common size of vectors supplied in `...`. If `NULL`, this
#' will be computed as the common size of the inputs.
#' @param .unpack Should unnamed data frame inputs be unpacked? Defaults to
#' `TRUE`.
#' @param .name_repair One of `"check_unique"`, `"unique"`, `"universal"`,
#' `"minimal"`, `"unique_quiet"`, or `"universal_quiet"`. See [vec_as_names()]
#' for the meaning of these options.
#'
#' @export
#' @examples
#' # `new_data_frame()` can be used to create custom data frame constructors
#' new_fancy_df <- function(x = list(), n = NULL, ..., class = NULL) {
#' new_data_frame(x, n = n, ..., class = c(class, "fancy_df"))
#' }
#'
#' # Combine this constructor with `df_list()` to create a safe,
#' # consistent helper function for your data frame subclass
#' fancy_df <- function(...) {
#' data <- df_list(...)
#' new_fancy_df(data)
#' }
#'
#' df <- fancy_df(x = 1)
#' class(df)
df_list <- function(...,
.size = NULL,
.unpack = TRUE,
.name_repair = c("check_unique", "unique", "universal", "minimal", "unique_quiet", "universal_quiet"),
.error_call = current_env()) {
.Call(ffi_df_list, list2(...), .size, .unpack, .name_repair, environment())
}
df_list <- fn_inline_formals(df_list, ".name_repair")
#' Construct a data frame
#'
#' @description
#' `data_frame()` constructs a data frame. It is similar to
#' [base::data.frame()], but there are a few notable differences that make it
#' more in line with vctrs principles. The Properties section outlines these.
#'
#' @details
#' If no column names are supplied, `""` will be used as a default name for all
#' columns. This is applied before name repair occurs, so the default name
#' repair of `"check_unique"` will error if any unnamed inputs are supplied and
#' `"unique"` (or `"unique_quiet"`) will repair the empty string column names
#' appropriately. If the column names don't matter, use a `"minimal"` name
#' repair for convenience and performance.
#'
#' @inheritSection df_list Properties
#'
#' @seealso
#' [df_list()] for safely creating a data frame's underlying data structure from
#' individual columns. [new_data_frame()] for constructing the actual data
#' frame from that underlying data structure. Together, these can be useful
#' for developers when creating new data frame subclasses supporting
#' standard evaluation.
#'
#' @inheritParams rlang::args_error_context
#'
#' @param ... Vectors to become columns in the data frame. When inputs are
#' named, those names are used for column names.
#' @param .size The number of rows in the data frame. If `NULL`, this will
#' be computed as the common size of the inputs.
#' @param .name_repair One of `"check_unique"`, `"unique"`, `"universal"`,
#' `"minimal"`, `"unique_quiet"`, or `"universal_quiet"`. See [vec_as_names()]
#' for the meaning of these options.
#'
#' @export
#' @examples
#' data_frame(x = 1, y = 2)
#'
#' # Inputs are recycled using tidyverse recycling rules
#' data_frame(x = 1, y = 1:3)
#'
#' # Strings are never converted to factors
#' class(data_frame(x = "foo")$x)
#'
#' # List columns can be easily created
#' df <- data_frame(x = list(1:2, 2, 3:4), y = 3:1)
#'
#' # However, the base print method is suboptimal for displaying them,
#' # so it is recommended to convert them to tibble
#' if (rlang::is_installed("tibble")) {
#' tibble::as_tibble(df)
#' }
#'
#' # Named data frame inputs create data frame columns
#' df <- data_frame(x = data_frame(y = 1:2, z = "a"))
#'
#' # The `x` column itself is another data frame
#' df$x
#'
#' # Again, it is recommended to convert these to tibbles for a better
#' # print method
#' if (rlang::is_installed("tibble")) {
#' tibble::as_tibble(df)
#' }
#'
#' # Unnamed data frame input is automatically unpacked
#' data_frame(x = 1, data_frame(y = 1:2, z = "a"))
data_frame <- function(...,
.size = NULL,
.name_repair = c("check_unique", "unique", "universal", "minimal", "unique_quiet", "universal_quiet"),
.error_call = current_env()) {
.Call(ffi_data_frame, list2(...), .size, .name_repair, environment())
}
data_frame <- fn_inline_formals(data_frame, ".name_repair")
#' @export
vec_ptype_abbr.data.frame <- function(x, ...) {
"df"
}
# For testing
# Keep in sync with `enum vctrs_proxy_kind` in `vctrs.h`
df_proxy <- function(x, kind) {
.Call(ffi_df_proxy, x, kind)
}
VCTRS_PROXY_KIND_equal <- 0L
VCTRS_PROXY_KIND_compare <- 1L
VCTRS_PROXY_KIND_order <- 2L
df_is_coercible <- function(x, y, opts) {
vec_is_coercible(
new_data_frame(x),
new_data_frame(y),
opts = opts
)
}
# Coercion ----------------------------------------------------------------
#' Coercion between two data frames
#'
#' `df_ptype2()` and `df_cast()` are the two functions you need to
#' call from `vec_ptype2()` and `vec_cast()` methods for data frame
#' subclasses. See [?howto-faq-coercion-data-frame][howto-faq-coercion-data-frame].
#' Their main job is to determine the common type of two data frames,
#' adding and coercing columns as needed, or throwing an incompatible
#' type error when the columns are not compatible.
#'
#' @param x,y,to Subclasses of data frame.
#' @param ... If you call `df_ptype2()` or `df_cast()` from a
#' `vec_ptype2()` or `vec_cast()` method, you must forward the dots
#' passed to your method on to `df_ptype2()` or `df_cast()`.
#' @inheritParams vec_ptype2
#' @inheritParams vec_cast
#'
#' @return
#' * When `x` and `y` are not compatible, an error of class
#' `vctrs_error_incompatible_type` is thrown.
#' * When `x` and `y` are compatible, `df_ptype2()` returns the common
#' type as a bare data frame. `tib_ptype2()` returns the common type
#' as a bare tibble.
#'
#' @export
df_ptype2 <- function(x,
y,
...,
x_arg = "",
y_arg = "",
call = caller_env()) {
.Call(
ffi_df_ptype2_opts,
x,
y,
opts = match_fallback_opts(...),
environment()
)
}
#' @rdname df_ptype2
#' @export
df_cast <- function(x,
to,
...,
x_arg = "",
to_arg = "",
call = caller_env()) {
.Call(
ffi_df_cast_opts,
x,
to,
opts = match_fallback_opts(...),
environment()
)
}
df_ptype2_opts <- function(x,
y,
...,
opts,
x_arg = "",
y_arg = "",
call = caller_env()) {
.Call(ffi_df_ptype2_opts, x, y, opts = opts, environment())
}
df_cast_opts <- function(x,
to,
...,
opts = fallback_opts(),
x_arg = "",
to_arg = "",
call = caller_env()) {
.Call(
ffi_df_cast_opts,
x,
to,
opts,
environment()
)
}
df_cast_params <- function(x,
to,
...,
x_arg = "",
to_arg = "",
s3_fallback = NULL) {
opts <- fallback_opts(s3_fallback = s3_fallback)
df_cast_opts(x, to, opts = opts, x_arg = x_arg, to_arg = to_arg)
}
#' vctrs methods for data frames
#'
#' These functions help the base data.frame class fit into the vctrs type system
#' by providing coercion and casting functions.
#'
#' @keywords internal
#' @name vctrs-data-frame
NULL
#' @rdname vctrs-data-frame
#' @export vec_ptype2.data.frame
#' @method vec_ptype2 data.frame
#' @export
vec_ptype2.data.frame <- function(x, y, ...) {
UseMethod("vec_ptype2.data.frame")
}
#' @method vec_ptype2.data.frame data.frame
#' @export
vec_ptype2.data.frame.data.frame <- function(x, y, ...) {
df_ptype2(x, y, ...)
}
# Fallback for data frame subclasses (#981)
vec_ptype2_df_fallback <- function(x,
y,
opts,
x_arg = "",
y_arg = "",
call = caller_env()) {
vec_ptype2_params(
as_base_df(x),
as_base_df(y),
s3_fallback = opts$s3_fallback,
x_arg = x_arg,
y_arg = y_arg,
call = call
)
}
as_base_df <- function(x) {
if (inherits(x, "tbl_df")) {
new_data_frame(x, class = c("tbl_df", "tbl"))
} else {
new_data_frame(x)
}
}
# Cast --------------------------------------------------------------------
#' @rdname vctrs-data-frame
#' @export vec_cast.data.frame
#' @method vec_cast data.frame
#' @export
vec_cast.data.frame <- function(x, to, ...) {
UseMethod("vec_cast.data.frame")
}
#' @export
#' @method vec_cast.data.frame data.frame
vec_cast.data.frame.data.frame <- function(x, to, ..., x_arg = "", to_arg = "") {
df_cast(x, to, ..., x_arg = x_arg, to_arg = to_arg)
}
#' @export
vec_restore.data.frame <- function(x, to, ...) {
.Call(ffi_vec_bare_df_restore, x, to)
}
# Helpers -----------------------------------------------------------------
df_size <- function(x) {
.Call(vctrs_df_size, x)
}
df_lossy_cast <- function(out,
x,
to,
...,
x_arg = "",
to_arg = "",
call = caller_env()) {
extra <- setdiff(names(x), names(to))
maybe_lossy_cast(
result = out,
x = x,
to = to,
lossy = length(extra) > 0,
locations = int(),
x_arg = x_arg,
to_arg = to_arg,
call = call,
details = inline_list("Dropped variables: ", extra, quote = "`"),
class = "vctrs_error_cast_lossy_dropped"
)
}
is_informative_error_vctrs_error_cast_lossy_dropped <- function(x, ...) {
FALSE
}
df_attrib <- function(x) {
attributes(x)[c("row.names", "names")]
}
non_df_attrib <- function(x) {
attrib <- attributes(x)
attrib <- attrib[!names(attrib) %in% c("row.names", "names")]
# Sort to allow comparison
attrib[order(names(attrib))]
}
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/type-data-frame.R
|
delayedAssign("as.data.table", {
if (is_installed("data.table")) {
env_get(ns_env("data.table"), "as.data.table")
} else {
function(...) abort("`data.table` must be installed.")
}
})
dt_ptype2 <- function(x, y, ...) {
as.data.table(df_ptype2(x, y, ...))
}
dt_cast <- function(x, to, ...) {
as.data.table(df_cast(x, to, ...))
}
#' @export
vec_ptype2.data.table.data.table <- function(x, y, ...) {
dt_ptype2(x, y, ...)
}
#' @export
vec_ptype2.data.table.data.frame <- function(x, y, ...) {
dt_ptype2(x, y, ...)
}
#' @export
vec_ptype2.data.frame.data.table <- function(x, y, ...) {
dt_ptype2(x, y, ...)
}
#' @export
vec_cast.data.table.data.table <- function(x, to, ...) {
dt_cast(x, to, ...)
}
#' @export
vec_cast.data.table.data.frame <- function(x, to, ...) {
dt_cast(x, to, ...)
}
#' @export
vec_cast.data.frame.data.table <- function(x, to, ...) {
df_cast(x, to, ...)
}
#' @export
vec_ptype_abbr.data.table <- function(x, ...) {
"dt"
}
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/type-data-table.R
|
#' Date, date-time, and duration S3 classes
#'
#' * A `date` ([Date]) is a double vector. Its value represent the number
#' of days since the Unix "epoch", 1970-01-01. It has no attributes.
#' * A `datetime` ([POSIXct] is a double vector. Its value represents the
#' number of seconds since the Unix "Epoch", 1970-01-01. It has a single
#' attribute: the timezone (`tzone`))
#' * A `duration` ([difftime])
#'
#' These function help the base `Date`, `POSIXct`, and `difftime` classes fit
#' into the vctrs type system by providing constructors, coercion functions,
#' and casting functions.
#'
#' @param x A double vector representing the number of days since UNIX
#' epoch for `new_date()`, number of seconds since UNIX epoch for
#' `new_datetime()`, and number of `units` for `new_duration()`.
#' @param tzone Time zone. A character vector of length 1. Either `""` for
#' the local time zone, or a value from [OlsonNames()]
#' @param units Units of duration.
#' @export
#' @keywords internal
#' @examples
#' new_date(0)
#' new_datetime(0, tzone = "UTC")
#' new_duration(1, "hours")
new_date <- function(x = double()) {
.Call(vctrs_new_date, x)
}
#' @export
#' @rdname new_date
new_datetime <- function(x = double(), tzone = "") {
.Call(vctrs_new_datetime, x, tzone)
}
#' @export
#' @rdname new_date
new_duration <- function(x = double(), units = c("secs", "mins", "hours", "days", "weeks")) {
stopifnot(is.double(x))
units <- arg_match0(units, c("secs", "mins", "hours", "days", "weeks"))
structure(
x,
units = units,
class = "difftime"
)
}
#' @export
vec_proxy.Date <- function(x, ...) {
date_validate(x)
}
#' @export
vec_proxy.POSIXct <- function(x, ...) {
datetime_validate(x)
}
#' @export
vec_proxy.POSIXlt <- function(x, ...) {
new_data_frame(unclass(x))
}
#' @export
vec_proxy_equal.POSIXlt <- function(x, ...) {
x <- vec_cast(x, new_datetime(tzone = tzone(x)))
vec_proxy_equal(x, ...)
}
#' @export
vec_proxy_compare.POSIXlt <- function(x, ...) {
x <- vec_cast(x, new_datetime(tzone = tzone(x)))
vec_proxy_compare(x)
}
#' @export
vec_restore.Date <- function(x, to, ...) {
NextMethod()
}
#' @export
vec_restore.POSIXct <- function(x, to, ...) {
NextMethod()
}
#' @export
vec_restore.POSIXlt <- function(x, to, ...) {
NextMethod()
}
# Print ------------------------------------------------------------------
#' @export
vec_ptype_full.Date <- function(x, ...) {
"date"
}
#' @export
vec_ptype_abbr.Date <- function(x, ...) {
"date"
}
#' @export
vec_ptype_full.POSIXct <- function(x, ...) {
tzone <- if (tzone_is_local(x)) "local" else tzone(x)
paste0("datetime<", tzone, ">")
}
#' @export
vec_ptype_full.POSIXlt <- function(x, ...) {
tzone <- if (tzone_is_local(x)) "local" else tzone(x)
paste0("POSIXlt<", tzone, ">")
}
#' @export
vec_ptype_abbr.POSIXct <- function(x, ...) {
"dttm"
}
#' @export
vec_ptype_abbr.POSIXlt <- function(x, ...) {
"dttm"
}
#' @export
vec_ptype_full.difftime <- function(x, ...) {
paste0("duration<", attr(x, "units"), ">")
}
#' @export
vec_ptype_abbr.difftime <- function(x, ...) {
"drtn"
}
# Coerce ------------------------------------------------------------------
#' @rdname new_date
#' @export vec_ptype2.Date
#' @method vec_ptype2 Date
#' @export
vec_ptype2.Date <- function(x, y, ...) {
UseMethod("vec_ptype2.Date")
}
#' @method vec_ptype2.Date Date
#' @export
vec_ptype2.Date.Date <- function(x, y, ...) {
stop_native_implementation("vec_ptype2.Date.Date")
}
#' @method vec_ptype2.Date POSIXct
#' @export
vec_ptype2.Date.POSIXct <- function(x, y, ...) {
stop_native_implementation("vec_ptype2.Date.POSIXct")
}
#' @method vec_ptype2.Date POSIXlt
#' @export
vec_ptype2.Date.POSIXlt <- function(x, y, ...) {
stop_native_implementation("vec_ptype2.Date.POSIXlt")
}
#' @rdname new_date
#' @export vec_ptype2.POSIXct
#' @method vec_ptype2 POSIXct
#' @export
vec_ptype2.POSIXct <- function(x, y, ...) {
UseMethod("vec_ptype2.POSIXct")
}
#' @method vec_ptype2.POSIXct POSIXct
#' @export
vec_ptype2.POSIXct.POSIXct <- function(x, y, ...) {
stop_native_implementation("vec_ptype2.POSIXct.POSIXct")
}
#' @method vec_ptype2.POSIXct Date
#' @export
vec_ptype2.POSIXct.Date <- function(x, y, ...) {
stop_native_implementation("vec_ptype2.POSIXct.Date")
}
#' @method vec_ptype2.POSIXct POSIXlt
#' @export
vec_ptype2.POSIXct.POSIXlt <- function(x, y, ...) {
stop_native_implementation("vec_ptype2.POSIXct.POSIXlt")
}
#' @rdname new_date
#' @export vec_ptype2.POSIXlt
#' @method vec_ptype2 POSIXlt
#' @export
vec_ptype2.POSIXlt <- function(x, y, ...) {
UseMethod("vec_ptype2.POSIXlt")
}
#' @method vec_ptype2.POSIXlt POSIXlt
#' @export
vec_ptype2.POSIXlt.POSIXlt <- function(x, y, ...) {
stop_native_implementation("vec_ptype2.POSIXlt.POSIXlt")
}
#' @method vec_ptype2.POSIXlt Date
#' @export
vec_ptype2.POSIXlt.Date <- function(x, y, ...) {
stop_native_implementation("vec_ptype2.POSIXlt.Date")
}
#' @method vec_ptype2.POSIXlt POSIXct
#' @export
vec_ptype2.POSIXlt.POSIXct <- function(x, y, ...) {
stop_native_implementation("vec_ptype2.POSIXlt.POSIXct")
}
#' @rdname new_date
#' @export vec_ptype2.difftime
#' @method vec_ptype2 difftime
#' @export
vec_ptype2.difftime <- function(x, y, ...) UseMethod("vec_ptype2.difftime")
#' @method vec_ptype2.difftime difftime
#' @export
vec_ptype2.difftime.difftime <- function(x, y, ...) new_duration(units = units_union(x, y))
# Cast --------------------------------------------------------------------
#' @rdname new_date
#' @export vec_cast.Date
#' @method vec_cast Date
#' @export
vec_cast.Date <- function(x, to, ...) {
UseMethod("vec_cast.Date")
}
#' @export
#' @method vec_cast.Date Date
vec_cast.Date.Date <- function(x, to, ...) {
stop_native_implementation("vec_cast.Date.Date")
}
#' @export
#' @method vec_cast.Date POSIXct
vec_cast.Date.POSIXct <- function(x, to, ...) {
# TODO: Mark with `stop_native_implementation()` when we use lazy errors
date_cast(x, to, ...)
}
#' @export
#' @method vec_cast.Date POSIXlt
vec_cast.Date.POSIXlt <- function(x, to, ...) {
# TODO: Mark with `stop_native_implementation()` when we use lazy errors
date_cast(x, to, ...)
}
# TODO: Remove when we have lazy errors
date_cast <- function(x, to, ..., x_arg = "", to_arg = "") {
out <- as.Date(x, tz = tzone(x))
x_ct <- as.POSIXct(x)
out_ct <- as.POSIXct(as.character(out), tz = tzone(x))
lossy <- abs(x_ct - out_ct) > 1e-9 & !is.na(x)
maybe_lossy_cast(out, x, to, lossy, x_arg = x_arg, to_arg = to_arg)
}
#' @rdname new_date
#' @export vec_cast.POSIXct
#' @method vec_cast POSIXct
#' @export
vec_cast.POSIXct <- function(x, to, ...) {
UseMethod("vec_cast.POSIXct")
}
#' @export
#' @method vec_cast.POSIXct Date
vec_cast.POSIXct.Date <- function(x, to, ...) {
stop_native_implementation("vec_cast.POSIXct.Date")
}
#' @export
#' @method vec_cast.POSIXct POSIXlt
vec_cast.POSIXct.POSIXlt <- function(x, to, ...) {
stop_native_implementation("vec_cast.POSIXct.POSIXlt")
}
#' @export
#' @method vec_cast.POSIXct POSIXct
vec_cast.POSIXct.POSIXct <- function(x, to, ...) {
stop_native_implementation("vec_cast.POSIXct.POSIXct")
}
#' @rdname new_date
#' @export vec_cast.POSIXlt
#' @method vec_cast POSIXlt
#' @export
vec_cast.POSIXlt <- function(x, to, ...) {
UseMethod("vec_cast.POSIXlt")
}
#' @export
#' @method vec_cast.POSIXlt Date
vec_cast.POSIXlt.Date <- function(x, to, ...) {
stop_native_implementation("vec_cast.POSIXlt.Date")
}
#' @export
#' @method vec_cast.POSIXlt POSIXlt
vec_cast.POSIXlt.POSIXlt <- function(x, to, ...) {
stop_native_implementation("vec_cast.POSIXlt.POSIXlt")
}
#' @export
#' @method vec_cast.POSIXlt POSIXct
vec_cast.POSIXlt.POSIXct <- function(x, to, ...) {
stop_native_implementation("vec_cast.POSIXlt.POSIXct")
}
#' @rdname new_date
#' @export vec_cast.difftime
#' @method vec_cast difftime
#' @export
vec_cast.difftime <- function(x, to, ...) {
UseMethod("vec_cast.difftime")
}
#' @export
#' @method vec_cast.difftime difftime
vec_cast.difftime.difftime <- function(x, to, ...) {
if (identical(units(x), units(to))) {
if (typeof(x) == "integer") {
# Catch corrupt difftime objects (#1602)
storage.mode(x) <- "double"
}
x
} else {
# Hack: I can't see any obvious way of changing the units
origin <- as.POSIXct(0, origin = "1970-01-01")
difftime(origin, origin - x, units = units(to))
}
}
# Arithmetic --------------------------------------------------------------
#' @rdname new_date
#' @export vec_arith.Date
#' @method vec_arith Date
#' @export
vec_arith.Date <- function(op, x, y, ...) UseMethod("vec_arith.Date", y)
#' @rdname new_date
#' @export vec_arith.POSIXct
#' @method vec_arith POSIXct
#' @export
vec_arith.POSIXct <- function(op, x, y, ...) UseMethod("vec_arith.POSIXct", y)
#' @rdname new_date
#' @export vec_arith.POSIXlt
#' @method vec_arith POSIXlt
#' @export
vec_arith.POSIXlt <- function(op, x, y, ...) UseMethod("vec_arith.POSIXlt", y)
#' @rdname new_date
#' @export vec_arith.difftime
#' @method vec_arith difftime
#' @export
vec_arith.difftime <- function(op, x, y, ...) UseMethod("vec_arith.difftime", y)
#' @method vec_arith.Date default
#' @export
vec_arith.Date.default <- function(op, x, y, ...) stop_incompatible_op(op, x, y)
#' @method vec_arith.POSIXct default
#' @export
vec_arith.POSIXct.default <- function(op, x, y, ...) stop_incompatible_op(op, x, y)
#' @method vec_arith.POSIXlt default
#' @export
vec_arith.POSIXlt.default <- function(op, x, y, ...) stop_incompatible_op(op, x, y)
#' @method vec_arith.difftime default
#' @export
vec_arith.difftime.default <- function(op, x, y, ...) stop_incompatible_op(op, x, y)
#' @method vec_arith.Date Date
#' @export
vec_arith.Date.Date <- function(op, x, y, ...) {
switch(op,
`-` = difftime(x, y, units = "days"),
stop_incompatible_op(op, x, y)
)
}
#' @method vec_arith.POSIXct POSIXct
#' @export
vec_arith.POSIXct.POSIXct <- function(op, x, y, ...) {
switch(op,
`-` = difftime(x, y, units = "secs"),
stop_incompatible_op(op, x, y)
)
}
#' @method vec_arith.POSIXlt POSIXlt
#' @export
vec_arith.POSIXlt.POSIXlt <- vec_arith.POSIXct.POSIXct
#' @method vec_arith.POSIXct Date
#' @export
vec_arith.POSIXct.Date <- vec_arith.POSIXct.POSIXct
#' @method vec_arith.Date POSIXct
#' @export
vec_arith.Date.POSIXct <- vec_arith.POSIXct.POSIXct
#' @method vec_arith.POSIXlt Date
#' @export
vec_arith.POSIXlt.Date <- vec_arith.POSIXct.POSIXct
#' @method vec_arith.Date POSIXlt
#' @export
vec_arith.Date.POSIXlt <- vec_arith.POSIXct.POSIXct
#' @method vec_arith.POSIXlt POSIXct
#' @export
vec_arith.POSIXlt.POSIXct <- vec_arith.POSIXct.POSIXct
#' @method vec_arith.POSIXct POSIXlt
#' @export
vec_arith.POSIXct.POSIXlt <- vec_arith.POSIXct.POSIXct
#' @method vec_arith.Date numeric
#' @export
vec_arith.Date.numeric <- function(op, x, y, ...) {
switch(op,
`+` = vec_restore(vec_arith_base(op, x, y), x),
`-` = vec_restore(vec_arith_base(op, x, y), x),
stop_incompatible_op(op, x, y)
)
}
#' @method vec_arith.numeric Date
#' @export
vec_arith.numeric.Date <- function(op, x, y, ...) {
switch(op,
`+` = vec_restore(vec_arith_base(op, x, y), y),
stop_incompatible_op(op, x, y)
)
}
#' @method vec_arith.POSIXct numeric
#' @export
vec_arith.POSIXct.numeric <- vec_arith.Date.numeric
#' @method vec_arith.numeric POSIXct
#' @export
vec_arith.numeric.POSIXct <- vec_arith.numeric.Date
#' @method vec_arith.POSIXlt numeric
#' @export
vec_arith.POSIXlt.numeric <- function(op, x, y, ...) {
vec_arith.POSIXct.numeric(op, as.POSIXct(x), y, ...)
}
#' @method vec_arith.numeric POSIXlt
#' @export
vec_arith.numeric.POSIXlt <- function(op, x, y, ...) {
vec_arith.numeric.POSIXct(op, x, as.POSIXct(y), ...)
}
#' @method vec_arith.Date difftime
#' @export
vec_arith.Date.difftime <- function(op, x, y, ...) {
y <- vec_cast(y, new_duration(units = "days"))
switch(op,
`+` = ,
`-` = vec_restore(vec_arith_base(op, x, lossy_floor(y, x)), x),
stop_incompatible_op(op, x, y)
)
}
#' @method vec_arith.difftime Date
#' @export
vec_arith.difftime.Date <- function(op, x, y, ...) {
x <- vec_cast(x, new_duration(units = "days"))
switch(op,
`+` = vec_restore(vec_arith_base(op, lossy_floor(x, y), y), y),
stop_incompatible_op(op, x, y)
)
}
#' @method vec_arith.POSIXct difftime
#' @export
vec_arith.POSIXct.difftime <- function(op, x, y, ...) {
y <- vec_cast(y, new_duration(units = "secs"))
switch(op,
`+` = vec_restore(vec_arith_base(op, x, y), x),
`-` = vec_restore(vec_arith_base(op, x, y), x),
stop_incompatible_op(op, x, y)
)
}
#' @method vec_arith.difftime POSIXct
#' @export
vec_arith.difftime.POSIXct <- function(op, x, y, ...) {
x <- vec_cast(x, new_duration(units = "secs"))
switch(op,
`+` = vec_restore(vec_arith_base(op, x, y), y),
stop_incompatible_op(op, x, y)
)
}
#' @method vec_arith.POSIXlt difftime
#' @export
vec_arith.POSIXlt.difftime <- function(op, x, y, ...) {
vec_arith.POSIXct.difftime(op, as.POSIXct(x), y, ...)
}
#' @method vec_arith.difftime POSIXlt
#' @export
vec_arith.difftime.POSIXlt <- function(op, x, y, ...) {
vec_arith.difftime.POSIXct(op, x, as.POSIXct(y), ...)
}
#' @method vec_arith.difftime difftime
#' @export
vec_arith.difftime.difftime <- function(op, x, y, ...) {
# Ensure x and y have same units
args <- vec_cast_common(x, y)
x <- args[[1L]]
y <- args[[2L]]
switch(op,
`+` = vec_restore(vec_arith_base(op, x, y), x),
`-` = vec_restore(vec_arith_base(op, x, y), x),
`/` = vec_arith_base(op, x, y),
`%/%` = vec_arith_base(op, x, y),
`%%` = vec_arith_base(op, x, y),
stop_incompatible_op(op, x, y)
)
}
#' @method vec_arith.difftime MISSING
#' @export
vec_arith.difftime.MISSING <- function(op, x, y, ...) {
switch(op,
`-` = vec_restore(-vec_data(x), x),
`+` = x,
stop_incompatible_op(op, x, y)
)
}
#' @method vec_arith.difftime numeric
#' @export
vec_arith.difftime.numeric <- function(op, x, y, ...) {
vec_restore(vec_arith_base(op, x, y), x)
}
#' @method vec_arith.numeric difftime
#' @export
vec_arith.numeric.difftime <- function(op, x, y, ...) {
switch(op,
`/` = stop_incompatible_op(op, x, y),
vec_restore(vec_arith_base(op, x, y), y)
)
}
# Helpers -----------------------------------------------------------------
# The tz attribute for POSIXlt can have 3 components
# (time zone name, abbreviated name, abbreviated DST name)
tzone <- function(x) {
attr(x, "tzone")[[1]] %||% ""
}
tzone_is_local <- function(x) {
identical(tzone(x), "")
}
tzone_union <- function(x, y) {
if (tzone_is_local(x)) {
tzone(y)
} else {
tzone(x)
}
}
units_union <- function(x, y) {
if (identical(units(x), units(y))) {
units(x)
} else {
"secs"
}
}
date_validate <- function(x) {
.Call(vctrs_date_validate, x)
}
datetime_validate <- function(x) {
.Call(vctrs_datetime_validate, x)
}
# as.character.Date() calls format() which tries to guess a simplified format.
# Supplying a known format is faster and much more memory efficient.
date_as_character <- function(x) {
format(x, format = "%Y-%m-%d")
}
# `as.POSIXlt.character()` tries multiple formats. Supplying
# a known format is much faster and more memory efficient.
chr_date_as_posixlt <- function(x, tzone) {
as.POSIXlt.character(x, tz = tzone, format = "%Y-%m-%d")
}
# `as.POSIXct.default()` for characters goes through `as.POSIXlt.character()`
chr_date_as_posixct <- function(x, tzone) {
out <- chr_date_as_posixlt(x, tzone)
as.POSIXct.POSIXlt(out, tzone)
}
lossy_floor <- function(x, to, x_arg = "", to_arg = "") {
x_floor <- floor(x)
lossy <- x != x_floor
maybe_lossy_cast(x_floor, x, to, lossy, x_arg = x_arg, to_arg = to_arg)
}
# Guarantees the presence of a `tzone` attribute
# by going through `as.POSIXlt.POSIXct()`.
# Useful for testing, since we always try to restore a `tzone`.
as_posixlt <- function(x, tz = "") {
as.POSIXlt(as.POSIXct(x, tz))
}
# Math --------------------------------------------------------------------
#' @export
vec_math.Date <- function(.fn, .x, ...) {
stop_unsupported(.x, .fn)
}
#' @export
vec_math.POSIXct <- function(.fn, .x, ...) {
stop_unsupported(.x, .fn)
}
#' @export
vec_math.POSIXlt <- function(.fn, .x, ...) {
stop_unsupported(.x, .fn)
}
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/type-date-time.R
|
# All methods in this file are conditionally registered in .onLoad()
### `grouped_df` -----------------------------------------------------
group_intersect <- function(x, new) {
intersect(dplyr::group_vars(x), names(new))
}
vec_restore_grouped_df <- function(x, to, ...) {
vars <- group_intersect(to, x)
drop <- dplyr::group_by_drop_default(to)
dplyr::grouped_df(x, vars, drop = drop)
}
# `vec_ptype2()` -----------------------------------------------------
vec_ptype2_grouped_df_grouped_df <- function(x, y, ...) {
gdf_ptype2(x, y, ...)
}
vec_ptype2_grouped_df_data.frame <- function(x, y, ...) {
gdf_ptype2(x, y, ...)
}
vec_ptype2_data.frame_grouped_df <- function(x, y, ...) {
gdf_ptype2(x, y, ...)
}
vec_ptype2_grouped_df_tbl_df <- function(x, y, ...) {
gdf_ptype2(x, y, ...)
}
vec_ptype2_tbl_df_grouped_df <- function(x, y, ...) {
gdf_ptype2(x, y, ...)
}
gdf_ptype2 <- function(x, y, ...) {
common <- df_ptype2(x, y, ...)
x_vars <- dplyr::group_vars(x)
y_vars <- dplyr::group_vars(y)
vars <- union(x_vars, y_vars)
drop <- dplyr::group_by_drop_default(x) && dplyr::group_by_drop_default(y)
dplyr::grouped_df(common, vars, drop = drop)
}
# `vec_cast()` -------------------------------------------------------
vec_cast_grouped_df_grouped_df <- function(x, to, ...) {
gdf_cast(x, to, ...)
}
vec_cast_grouped_df_data.frame <- function(x, to, ...) {
gdf_cast(x, to, ...)
}
vec_cast_data.frame_grouped_df <- function(x, to, ...) {
df_cast(x, to, ...)
}
vec_cast_grouped_df_tbl_df <- function(x, to, ...) {
gdf_cast(x, to, ...)
}
vec_cast_tbl_df_grouped_df <- function(x, to, ...) {
tib_cast(x, to, ...)
}
gdf_cast <- function(x, to, ...) {
df <- df_cast(x, to, ...)
vars <- dplyr::group_vars(to)
drop <- dplyr::group_by_drop_default(to)
dplyr::grouped_df(df, vars, drop = drop)
}
### `rowwise` --------------------------------------------------------
vec_restore_rowwise_df <- function(x, to, ...) {
dplyr::rowwise(x)
}
# `vec_ptype2()` -----------------------------------------------------
vec_ptype2_rowwise_df_rowwise_df <- function(x, y, ...) {
rww_ptype2(x, y, ...)
}
vec_ptype2_rowwise_df_data.frame <- function(x, y, ...) {
rww_ptype2(x, y, ...)
}
vec_ptype2_data.frame_rowwise_df <- function(x, y, ...) {
rww_ptype2(x, y, ...)
}
vec_ptype2_rowwise_df_tbl_df <- function(x, y, ...) {
rww_ptype2(x, y, ...)
}
vec_ptype2_tbl_df_rowwise_df <- function(x, y, ...) {
rww_ptype2(x, y, ...)
}
rww_ptype2 <- function(x, y, ...) {
dplyr::rowwise(df_ptype2(x, y, ...))
}
# `vec_cast()` -------------------------------------------------------
vec_cast_rowwise_df_rowwise_df <- function(x, to, ...) {
rww_cast(x, to, ...)
}
vec_cast_rowwise_df_data.frame <- function(x, to, ...) {
rww_cast(x, to, ...)
}
vec_cast_data.frame_rowwise_df <- function(x, to, ...) {
df_cast(x, to, ...)
}
vec_cast_rowwise_df_tbl_df <- function(x, to, ...) {
rww_cast(x, to, ...)
}
vec_cast_tbl_df_rowwise_df <- function(x, to, ...) {
tib_cast(x, to, ...)
}
rww_cast <- function(x, to, ...) {
dplyr::rowwise(df_cast(x, to, ...))
}
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/type-dplyr.R
|
coerces_to <- function(x, y, using = "strict") {
type_max <- switch(using,
strict = vec_ptype2,
base_c = c,
base_unlist = function(x, y) unlist(list(x, y)),
base_modify = function(x, y) `[<-`(x, 2, value = y)
)
tryCatch({
type <- suppressWarnings(type_max(x, y))
vec_ptype_full(type)
}, error = function(e) {
NA_character_
})
}
maxtype_mat <- function(types, using = "strict") {
names(types) <- map_chr(types, function(x) vec_ptype_full(vec_ptype(x)))
grid <- expand.grid(x = types, y = types)
grid$max <- map2_chr(grid$x, grid$y, coerces_to, using = using)
matrix(
grid$max,
nrow = length(types),
dimnames = list(names(types), names(types))
)
}
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/type-explore.R
|
#' Factor/ordered factor S3 class
#'
#' A [factor] is an integer with attribute `levels`, a character vector. There
#' should be one level for each integer between 1 and `max(x)`.
#' An [ordered] factor has the same properties as a factor, but possesses
#' an extra class that marks levels as having a total ordering.
#'
#' These functions help the base factor and ordered factor classes fit in to
#' the vctrs type system by providing constructors, coercion functions,
#' and casting functions. `new_factor()` and `new_ordered()` are low-level
#' constructors - they only check that types, but not values, are valid, so
#' are for expert use only.
#'
#' @param x Integer values which index in to `levels`.
#' @param levels Character vector of labels.
#' @param ...,class Used to for subclasses.
#' @keywords internal
#' @export
new_factor <- function(x = integer(), levels = character(), ..., class = character()) {
stopifnot(is.integer(x))
stopifnot(is.character(levels))
structure(
x,
levels = levels,
...,
class = c(class, "factor")
)
}
#' @export
#' @rdname new_factor
new_ordered <- function(x = integer(), levels = character()) {
new_factor(x = x, levels = levels, class = "ordered")
}
#' @export
vec_proxy.factor <- function(x, ...) {
x
}
#' @export
vec_proxy.ordered <- function(x, ...) {
x
}
#' @export
vec_restore.factor <- function(x, to, ...) {
NextMethod()
}
#' @export
vec_restore.ordered <- function(x, to, ...) {
NextMethod()
}
# Print -------------------------------------------------------------------
#' @export
vec_ptype_full.factor <- function(x, ...) {
paste0("factor<", hash_label(levels(x)), ">", vec_ptype_shape(x))
}
#' @export
vec_ptype_abbr.factor <- function(x, ...) {
"fct"
}
#' @export
vec_ptype_full.ordered <- function(x, ...) {
paste0("ordered<", hash_label(levels(x)), ">", vec_ptype_shape(x))
}
#' @export
vec_ptype_abbr.ordered <- function(x, ...) {
"ord"
}
# Coerce ------------------------------------------------------------------
#' @rdname new_factor
#' @export vec_ptype2.factor
#' @method vec_ptype2 factor
#' @export
vec_ptype2.factor <- function(x, y, ...) {
UseMethod("vec_ptype2.factor")
}
#' @export
vec_ptype2.factor.factor <- function(x, y, ...) {
stop_native_implementation("vec_ptype2.factor.factor")
}
#' @export
vec_ptype2.character.factor <- function(x, y, ...) {
stop_native_implementation("vec_ptype2.character.factor")
}
#' @export
vec_ptype2.factor.character <- function(x, y, ...) {
stop_native_implementation("vec_ptype2.factor.character")
}
#' @rdname new_factor
#' @export vec_ptype2.ordered
#' @method vec_ptype2 ordered
#' @export
vec_ptype2.ordered <- function(x, y, ...) {
UseMethod("vec_ptype2.ordered")
}
#' @export
vec_ptype2.ordered.ordered <- function(x, y, ...) {
stop_native_implementation("vec_ptype2.ordered.ordered")
}
#' @export
vec_ptype2.ordered.character <- function(x, y, ...) {
stop_native_implementation("vec_ptype2.ordered.character")
}
#' @export
vec_ptype2.character.ordered <- function(x, y, ...) {
stop_native_implementation("vec_ptype2.character.ordered")
}
#' @export
vec_ptype2.ordered.factor <- function(x, y, ...) {
vec_default_ptype2(x, y, ...)
}
#' @export
vec_ptype2.factor.ordered <- function(x, y, ...) {
vec_default_ptype2(x, y, ...)
}
# Cast --------------------------------------------------------------------
#' @rdname new_factor
#' @export vec_cast.factor
#' @method vec_cast factor
#' @export
vec_cast.factor <- function(x, to, ...) {
UseMethod("vec_cast.factor")
}
fct_cast <- function(x, to, ..., call = caller_env()) {
fct_cast_impl(x, to, ..., ordered = FALSE, call = call)
}
fct_cast_impl <- function(x,
to,
...,
x_arg = "",
to_arg = "",
ordered = FALSE,
call = caller_env()) {
if (length(levels(to)) == 0L) {
levels <- levels(x)
if (is.null(levels)) {
exclude <- NA
levels <- unique(x)
} else {
exclude <- NULL
}
factor(
as.character(x),
levels = levels,
ordered = ordered,
exclude = exclude
)
} else {
lossy <- !(x %in% levels(to) | is.na(x))
out <- factor(
x,
levels = levels(to),
ordered = ordered,
exclude = NULL
)
maybe_lossy_cast(
out,
x,
to,
lossy,
loss_type = "generality",
x_arg = x_arg,
to_arg = to_arg,
call = call
)
}
}
#' @export
vec_cast.factor.factor <- function(x, to, ...) {
fct_cast(x, to, ...)
}
#' @export
vec_cast.factor.character <-function(x, to, ...) {
fct_cast(x, to, ...)
}
#' @export
vec_cast.character.factor <- function(x, to, ...) {
stop_native_implementation("vec_cast.character.factor")
}
#' @rdname new_factor
#' @export vec_cast.ordered
#' @method vec_cast ordered
#' @export
vec_cast.ordered <- function(x, to, ...) {
UseMethod("vec_cast.ordered")
}
ord_cast <- function(x, to, ..., call = caller_env()) {
fct_cast_impl(x, to, ..., ordered = TRUE, call = call)
}
#' @export
vec_cast.ordered.ordered <- function(x, to, ...) {
ord_cast(x, to, ...)
}
#' @export
vec_cast.ordered.character <-function(x, to, ...) {
ord_cast(x, to, ...)
}
#' @export
vec_cast.character.ordered <- function(x, to, ...) {
stop_native_implementation("vec_cast.character.ordered")
}
# Math and arithmetic -----------------------------------------------------
#' @export
vec_math.factor <- function(.fn, .x, ...) {
stop_unsupported(.x, .fn)
}
#' @export
vec_arith.factor <- function(op, x, y, ...) {
stop_unsupported(x, op)
}
# Helpers -----------------------------------------------------------------
hash_label <- function(x, length = 5) {
if (length(x) == 0) {
""
} else {
# Can't use obj_hash() because it hashes the string pointers
# for performance, so the values in the test change each time
substr(rlang::hash(x), 1, length)
}
}
levels_union <- function(x, y) {
union(levels(x), levels(y))
}
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/type-factor.R
|
#' @export
vec_proxy_equal.integer64 <- function(x, ...) {
if (is.array(x)) {
# Stopgap to convert arrays to data frames, then run them through
# `vec_proxy_equal()` again, which will proxy each column
x <- as_data_frame_from_array(x)
x <- vec_proxy_equal(x)
return(x)
}
integer64_proxy(x)
}
# Print -------------------------------------------------------------------
#' 64 bit integers
#'
#' A `integer64` is a 64 bits integer vector, implemented in the `bit64` package.
#'
#' These functions help the `integer64` class from `bit64` in to
#' the vctrs type system by providing coercion functions
#' and casting functions.
#'
#' @keywords internal
#' @rdname int64
#' @export
vec_ptype_full.integer64 <- function(x, ...) {
"integer64"
}
#' @rdname int64
#' @export
vec_ptype_abbr.integer64 <- function(x, ...) {
"int64"
}
# Coerce ------------------------------------------------------------------
#' @export
#' @rdname int64
#' @export vec_ptype2.integer64
#' @method vec_ptype2 integer64
vec_ptype2.integer64 <- function(x, y, ...) {
UseMethod("vec_ptype2.integer64")
}
#' @method vec_ptype2.integer64 integer64
#' @export
vec_ptype2.integer64.integer64 <- function(x, y, ...) bit64::integer64()
#' @method vec_ptype2.integer64 integer
#' @export
vec_ptype2.integer64.integer <- function(x, y, ...) bit64::integer64()
#' @method vec_ptype2.integer integer64
#' @export
vec_ptype2.integer.integer64 <- function(x, y, ...) bit64::integer64()
#' @method vec_ptype2.integer64 logical
#' @export
vec_ptype2.integer64.logical <- function(x, y, ...) bit64::integer64()
#' @method vec_ptype2.logical integer64
#' @export
vec_ptype2.logical.integer64 <- function(x, y, ...) bit64::integer64()
# Cast --------------------------------------------------------------------
#' @export
#' @rdname int64
#' @export vec_cast.integer64
#' @method vec_cast integer64
vec_cast.integer64 <- function(x, to, ...) {
UseMethod("vec_cast.integer64")
}
#' @export
#' @method vec_cast.integer64 integer64
vec_cast.integer64.integer64 <- function(x, to, ...) {
x
}
#' @export
#' @method vec_cast.integer64 integer
vec_cast.integer64.integer <- function(x, to, ...) {
bit64::as.integer64(x)
}
#' @export
#' @method vec_cast.integer integer64
vec_cast.integer.integer64 <- function(x, to, ...) {
as.integer(x)
}
#' @export
#' @method vec_cast.integer64 logical
vec_cast.integer64.logical <- function(x, to, ...) {
bit64::as.integer64(x)
}
#' @export
#' @method vec_cast.logical integer64
vec_cast.logical.integer64 <- function(x, to, ...) {
as.logical(x)
}
#' @export
#' @method vec_cast.integer64 double
vec_cast.integer64.double <- function(x, to, ...) {
bit64::as.integer64(x)
}
#' @export
#' @method vec_cast.double integer64
vec_cast.double.integer64 <- function(x, to, ...) {
as.double(x)
}
# ------------------------------------------------------------------------------
integer64_proxy <- function(x) {
.Call(vctrs_integer64_proxy, x)
}
integer64_restore <- function(x) {
.Call(vctrs_integer64_restore, x)
}
# ------------------------------------------------------------------------------
as_data_frame_from_array <- function(x) {
# Alternative to `as.data.frame.array()` that always strips 1-D arrays
# of their dimensions. Unlike `as.data.frame2()`, it doesn't unclass the
# input, which means that each column retains its original class.
# This function doesn't attempt to keep the names of `x` at all.
dim <- dim(x)
n_dim <- length(dim)
if (n_dim == 1) {
# Treat 1-D arrays as 1 column matrices
dim(x) <- c(dim, 1L)
n_dim <- 2L
}
n_row <- dim[[1L]]
n_col <- prod(dim[-1L])
n_col_seq <- seq_len(n_col)
dim(x) <- c(n_row, n_col)
out <- vector("list", n_col)
names(out) <- as_unique_names(rep("", n_col), quiet = TRUE)
for (i in n_col_seq) {
out[[i]] <- x[, i, drop = TRUE]
}
new_data_frame(out, n = n_row)
}
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/type-integer64.R
|
#' `list_of` S3 class for homogenous lists
#'
#' A `list_of` object is a list where each element has the same type.
#' Modifying the list with `$`, `[`, and `[[` preserves the constraint
#' by coercing all input items.
#'
#' Unlike regular lists, setting a list element to `NULL` using `[[`
#' does not remove it.
#'
#' @inheritParams vec_c
#' @param x For `as_list_of()`, a vector to be coerced to list_of.
#' @param y,to Arguments to `vec_ptype2()` and `vec_cast()`.
#' @export
#' @examples
#' x <- list_of(1:3, 5:6, 10:15)
#' if (requireNamespace("tibble", quietly = TRUE)) {
#' tibble::tibble(x = x)
#' }
#'
#' vec_c(list_of(1, 2), list_of(FALSE, TRUE))
list_of <- function(..., .ptype = NULL) {
args <- list2(...)
list_as_list_of(args, ptype = .ptype)
}
#' @export
#' @rdname list_of
as_list_of <- function(x, ...) {
UseMethod("as_list_of")
}
#' @export
as_list_of.vctrs_list_of <- function(x, ..., .ptype = NULL) {
if (!is.null(.ptype)) {
x <- unclass(x)
list_as_list_of(x, ptype = .ptype)
} else {
x
}
}
#' @export
as_list_of.list <- function(x, ..., .ptype = NULL) {
list_as_list_of(x, ptype = .ptype)
}
#' Create list_of subclass
#'
#' @param x A list
#' @param ptype The prototype which every element of `x` belongs to
#' @param ... Additional attributes used by subclass
#' @param class Optional subclass name
#' @keywords internal
#' @export
new_list_of <- function(x = list(), ptype = logical(), ..., class = character()) {
if (!obj_is_list(x)) {
abort("`x` must be a list.")
}
if (vec_size(ptype) != 0L) {
abort("`ptype` must have size 0.")
}
new_list_of0(x = x, ptype = ptype, ..., class = class)
}
new_list_of0 <- function(x, ptype, ..., class = character()) {
new_vctr(x, ..., ptype = ptype, class = c(class, "vctrs_list_of"))
}
list_of_unstructure <- function(x) {
attr(x, "ptype") <- NULL
attr(x, "class") <- NULL
x
}
#' @export
#' @rdname list_of
is_list_of <- function(x) {
inherits(x, "vctrs_list_of")
}
#' @export
vec_proxy.vctrs_list_of <- function(x, ...) {
unclass(x)
}
# Formatting --------------------------------------------------------------
#' @export
obj_print_data.vctrs_list_of <- function(x, ...) {
if (length(x) == 0)
return()
print(vec_data(x))
}
#' @export
format.vctrs_list_of <- function(x, ...) {
format.default(x)
}
#' @export
vec_ptype_full.vctrs_list_of <- function(x, ...) {
param <- vec_ptype_full(attr(x, "ptype"))
if (grepl("\n", param)) {
param <- paste0(indent(paste0("\n", param), 2), "\n")
}
paste0("list_of<", param, ">")
}
#' @export
vec_ptype_abbr.vctrs_list_of <- function(x, ...) {
paste0("list<", vec_ptype_abbr(attr(x, "ptype")), ">")
}
# vctr methods ------------------------------------------------------------
#' @export
as.list.vctrs_list_of <- function(x, ...) {
list_of_unstructure(x)
}
#' @export
as.character.vctrs_list_of <- function(x, ...) {
# For compatibility with the RStudio Viewer. See tidyverse/tidyr#654.
map_chr(x, function(elt) paste0("<", vec_ptype_abbr(elt), ">"))
}
#' @export
`[[.vctrs_list_of` <- function(x, i, ...) {
.Call(vctrs_list_get, x, i)
}
#' @export
`$.vctrs_list_of` <- function(x, i, ...) {
.Call(vctrs_list_get, x, i)
}
#' @export
`[<-.vctrs_list_of` <- function(x, i, value) {
wrapped_type <- attr(x, "ptype")
value <- map(value, vec_cast, to = wrapped_type)
value <- new_list_of0(value, ptype = wrapped_type)
NextMethod()
}
#' @export
`[[<-.vctrs_list_of` <- function(x, i, value) {
if (is.null(value)) {
# Setting to NULL via [[ shortens the list! Example:
# `[[<-`(list(1), 1, NULL)
x[i] <- list(value)
return(x)
}
value <- vec_cast(value, attr(x, "ptype"))
NextMethod()
}
#' @export
`$<-.vctrs_list_of` <- function(x, i, value) {
value <- vec_cast(value, attr(x, "ptype"))
NextMethod()
}
# Type system -------------------------------------------------------------
#' @rdname list_of
#' @inheritParams vec_ptype2
#' @export vec_ptype2.vctrs_list_of
#' @method vec_ptype2 vctrs_list_of
#' @export
vec_ptype2.vctrs_list_of <- function(x, y, ..., x_arg = "", y_arg = "") {
UseMethod("vec_ptype2.vctrs_list_of")
}
#' @method vec_ptype2.vctrs_list_of vctrs_list_of
#' @export
vec_ptype2.vctrs_list_of.vctrs_list_of <- function(x, y, ..., x_arg = "", y_arg = "") {
x_ptype <- attr(x, "ptype", exact = TRUE)
y_ptype <- attr(y, "ptype", exact = TRUE)
if (identical(x_ptype, y_ptype)) {
return(x)
}
tryCatch(
expr = {
ptype <- vec_ptype2(x_ptype, y_ptype, x_arg = x_arg, y_arg = y_arg)
new_list_of0(x = list(), ptype = ptype)
},
vctrs_error_incompatible_type = function(cnd) {
list()
}
)
}
#' @export
vec_ptype2.list.vctrs_list_of <- function(x, y, ...) {
list()
}
#' @export
vec_ptype2.vctrs_list_of.list <- function(x, y, ...) {
list()
}
#' @rdname list_of
#' @export vec_cast.vctrs_list_of
#' @method vec_cast vctrs_list_of
#' @export
vec_cast.vctrs_list_of <- function(x, to, ...) {
UseMethod("vec_cast.vctrs_list_of")
}
#' @export
#' @method vec_cast.vctrs_list_of vctrs_list_of
vec_cast.vctrs_list_of.vctrs_list_of <- function(x, to, ..., call = caller_env()) {
x_ptype <- attr(x, "ptype", exact = TRUE)
to_ptype <- attr(to, "ptype", exact = TRUE)
if (identical(x_ptype, to_ptype)) {
# FIXME: Suboptimal check for "same type", but should be good enough for the
# common case of unchopping a list of identically generated list-ofs (#875).
# Would be fixed by https://github.com/r-lib/vctrs/issues/1688.
x
} else {
x <- unclass(x)
list_as_list_of(x, ptype = to_ptype, error_call = call)
}
}
#' @export
vec_cast.list.vctrs_list_of <-function(x, to, ...) {
list_of_unstructure(x)
}
#' @export
vec_cast.vctrs_list_of.list <-function(x, to, ..., call = caller_env()) {
list_as_list_of(
x,
attr(to, "ptype"),
error_call = call
)
}
# Helpers -----------------------------------------------------------------
list_as_list_of <- function(x, ptype = NULL, error_call = caller_env()) {
ptype <- vec_ptype_common(!!!x, .ptype = ptype, .call = error_call)
if (is.null(ptype)) {
abort("Can't find common type for elements of `x`.", call = error_call)
}
x <- vec_cast_common(!!!x, .to = ptype, .call = error_call)
new_list_of0(x = x, ptype = ptype)
}
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/type-list-of.R
|
# `numeric_version` from base ----------------------------------------
#' @export
vec_proxy.numeric_version <- function(x, ...) {
x
}
#' @export
vec_proxy_equal.numeric_version <- function(x, ...) {
proxy_equal_numeric_version(x)
}
# To generate data agnostic proxies of `<numeric_version>`, we enforce a
# restriction that each version can have at most 8 components. This allows us
# to `vec_compare()` them without needing a "joint" comparison proxy, unlike
# what `.encode_numeric_version()` returns.
proxy_equal_numeric_version <- function(x, error_call = caller_env()) {
N_COMPONENTS <- 8L
x <- unclass(x)
size <- length(x)
sizes <- lengths(x)
if (length(sizes) != 0L) {
max <- max(sizes)
} else {
max <- N_COMPONENTS
}
if (max > N_COMPONENTS) {
cli::cli_abort(
"`x` can't contain more than {N_COMPONENTS} version components.",
call = error_call
)
}
if (any(sizes != max)) {
# Pad with zeros where needed to be able to transpose.
# This is somewhat slow if required.
pad_sizes <- max - sizes
pad_needed <- which(pad_sizes != 0L)
x[pad_needed] <- map2(
x[pad_needed],
pad_sizes[pad_needed],
function(elt, pad_size) {
c(elt, vec_rep(0L, times = pad_size))
}
)
}
# Transpose with combination of `vec_interleave()` and `vec_chop()`
x <- vec_interleave(!!!x, .ptype = integer())
out <- vec_chop(x, sizes = vec_rep(size, times = max))
n_zeros <- N_COMPONENTS - max
if (n_zeros != 0L) {
# Pad columns of zeros out to `N_COMPONENTS` columns
zero <- list(vec_rep(0L, times = size))
out <- c(out, vec_rep(zero, times = n_zeros))
}
# Use a data frame as the proxy
names(out) <- paste0("...", seq_len(N_COMPONENTS))
out <- new_data_frame(out, n = size)
# A `<numeric_version>` internally stored as `integer()` is considered the
# `NA` value. We patch that in at the very end if needed. It is hard to create
# so should be very uncommon.
missing <- sizes == 0L
if (any(missing)) {
na <- vec_init(out)
out <- vec_assign(out, missing, na)
}
out
}
# `omit` from base ---------------------------------------------------
#' @export
vec_proxy.omit <- function(x, ...) {
x
}
#' @export
vec_restore.omit <- function(x, ...) {
structure(x, class = "omit")
}
#' @export
vec_ptype2.omit.omit <- function(x, y, ...) {
x
}
#' @export
vec_ptype2.integer.omit <- function(x, y, ...) {
x
}
#' @export
vec_ptype2.omit.integer <- function(x, y, ...) {
y
}
#' @export
vec_ptype2.double.omit <- function(x, y, ...) {
x
}
#' @export
vec_ptype2.omit.double <- function(x, y, ...) {
y
}
#' @export
vec_cast.omit.omit <- function(x, to, ...) {
x
}
#' @export
vec_cast.integer.omit <- function(x, to, ...) {
vec_cast(vec_data(x), to, ...)
}
#' @export
vec_cast.omit.integer <- function(x, to, ..., x_arg = "", to_arg = "") {
stop_incompatible_cast(x, to, x_arg = x_arg, to_arg = to_arg)
}
#' @export
vec_cast.double.omit <- function(x, to, ...) {
vec_cast(vec_data(x), to, ...)
}
#' @export
vec_cast.omit.double <- function(x, to, ..., x_arg = "", to_arg = "") {
stop_incompatible_cast(x, to, x_arg = x_arg, to_arg = to_arg)
}
# `exclude` from base ------------------------------------------------
#' @export
vec_proxy.exclude <- function(x, ...) {
x
}
#' @export
vec_restore.exclude <- function(x, ...) {
structure(x, class = "exclude")
}
#' @export
vec_ptype2.exclude.exclude <- function(x, y, ...) {
x
}
#' @export
vec_ptype2.integer.exclude <- function(x, y, ...) {
x
}
#' @export
vec_ptype2.exclude.integer <- function(x, y, ...) {
y
}
#' @export
vec_ptype2.double.exclude <- function(x, y, ...) {
x
}
#' @export
vec_ptype2.exclude.double <- function(x, y, ...) {
y
}
#' @export
vec_cast.exclude.exclude <- function(x, to, ...) {
x
}
#' @export
vec_cast.integer.exclude <- function(x, to, ...) {
vec_cast(vec_data(x), to, ...)
}
#' @export
vec_cast.exclude.integer <- function(x, to, ..., x_arg = "", to_arg = "") {
stop_incompatible_cast(x, to, x_arg = x_arg, to_arg = to_arg)
}
#' @export
vec_cast.double.exclude <- function(x, to, ...) {
vec_cast(vec_data(x), to, ...)
}
#' @export
vec_cast.exclude.double <- function(x, to, ..., x_arg = "", to_arg = "") {
stop_incompatible_cast(x, to, x_arg = x_arg, to_arg = to_arg)
}
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/type-misc.R
|
# Constructor and basic methods ---------------------------------------------
#' rcrd (record) S3 class
#'
#' The rcrd class extends [vctr]. A rcrd is composed of 1 or more [field]s,
#' which must be vectors of the same length. Is designed specifically for
#' classes that can naturally be decomposed into multiple vectors of the same
#' length, like [POSIXlt], but where the organisation should be considered
#' an implementation detail invisible to the user (unlike a [data.frame]).
#'
#' @param fields A list or a data frame. Lists must be rectangular
#' (same sizes), and contain uniquely named vectors (at least
#' one). `fields` is validated with [df_list()] to ensure uniquely
#' named vectors.
#' @param ... Additional attributes
#' @param class Name of subclass.
#' @export
#' @aliases ses rcrd
#' @keywords internal
new_rcrd <- function(fields, ..., class = character()) {
if (obj_is_list(fields) && length(vec_unique(list_sizes(fields))) > 1L) {
abort("All fields must be the same size.")
}
fields <- df_list(!!!fields)
if (!length(fields)) {
abort("`fields` must be a list of length 1 or greater.")
}
structure(fields, ..., class = c(class, "vctrs_rcrd", "vctrs_vctr"))
}
#' @export
vec_proxy.vctrs_rcrd <- function(x, ...) {
new_data_frame(x)
}
#' @export
vec_restore.vctrs_rcrd <- function(x, to, ...) {
x <- NextMethod()
attr(x, "row.names") <- NULL
x
}
#' @export
length.vctrs_rcrd <- function(x) {
vec_size(x)
}
#' @export
names.vctrs_rcrd <- function(x) {
NULL
}
#' @export
`names<-.vctrs_rcrd` <- function(x, value) {
if (is_null(value)) {
x
} else {
abort("Can't assign names to a <vctrs_rcrd>.")
}
}
#' @export
format.vctrs_rcrd <- function(x, ...) {
if (inherits(x, "vctrs_foobar")) {
# For unit tests
exec("paste", !!!vec_data(x), sep = ":")
} else {
stop_unimplemented(x, "format")
}
}
#' @export
obj_str_data.vctrs_rcrd <- function(x, ...) {
obj_str_leaf(x, ...)
}
#' @method vec_cast vctrs_rcrd
#' @export
vec_cast.vctrs_rcrd <- function(x, to, ...) UseMethod("vec_cast.vctrs_rcrd")
#' @export
vec_cast.vctrs_rcrd.vctrs_rcrd <- function(x, to, ...) {
out <- vec_cast(vec_data(x), vec_data(to), ...)
new_rcrd(out)
}
# Subsetting --------------------------------------------------------------
#' @export
`[.vctrs_rcrd` <- function(x, i, ...) {
if (!missing(...)) {
abort("Can't index record vectors on dimensions greater than 1.")
}
vec_slice(x, maybe_missing(i))
}
#' @export
`[[.vctrs_rcrd` <- function(x, i, ...) {
out <- vec_slice(vec_data(x), i)
vec_restore(out, x)
}
#' @export
`$.vctrs_rcrd` <- function(x, i, ...) {
stop_unsupported(x, "subsetting with $")
}
#' @export
rep.vctrs_rcrd <- function(x, ...) {
out <- lapply(vec_data(x), base_vec_rep, ...)
vec_restore(out, x)
}
#' @export
`length<-.vctrs_rcrd` <- function(x, value) {
out <- vec_size_assign(vec_data(x), value)
vec_restore(out, x)
}
# Replacement -------------------------------------------------------------
#' @export
`[[<-.vctrs_rcrd` <- function(x, i, value) {
force(i)
x[i] <- value
x
}
#' @export
`$<-.vctrs_rcrd` <- function(x, i, value) {
stop_unsupported(x, "subset assignment with $")
}
#' @export
`[<-.vctrs_rcrd` <- function(x, i, value) {
i <- maybe_missing(i, TRUE)
value <- vec_cast(value, x)
out <- vec_assign(vec_data(x), i, vec_data(value))
vec_restore(out, x)
}
# Equality and ordering ---------------------------------------------------
#' @export
vec_math.vctrs_rcrd <- function(.fn, .x, ...) {
stop_unsupported(.x, "vec_math")
}
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/type-rcrd.R
|
new_sclr <- function(..., class = character()) {
fields <- list(...)
stopifnot(has_unique_names(fields))
structure(
list(...),
class = c(class, "vctrs_sclr")
)
}
# Subsetting --------------------------------------------------------------
#' @export
`[[.vctrs_sclr` <- function(x, i, ...) {
.Call(vctrs_list_get, x, i)
}
#' @export
`$.vctrs_sclr` <- function(x, i, ...) {
.Call(vctrs_list_get, x, i)
}
#' @export
`[[<-.vctrs_sclr` <- function(x, i, value) {
.Call(vctrs_list_set, x, i, value)
}
#' @export
`$<-.vctrs_sclr` <- function(x, i, value) {
.Call(vctrs_list_set, x, i, value)
}
# Shared niceties ---------------------------------------------------------
#' @export
print.vctrs_sclr <- function(x, ...) {
obj_print(x, ...)
invisible(x)
}
#' @export
as.list.vctrs_sclr <- function(x, ...) {
vec_set_attributes(x, list(names = names(x)))
}
#' @export
as.data.frame.vctrs_sclr <- function(x,
row.names = NULL,
optional = FALSE,
...,
nm = paste(deparse(substitute(x), width.cutoff = 500L), collapse = " ")
) {
force(nm)
cols <- list(list(x))
if (!optional) {
names(cols) <- nm
}
new_data_frame(cols, n = 1L)
}
# Vector behaviours -------------------------------------------------------
#' @export
`[.vctrs_sclr` <- function(x, ...) {
stop_unsupported(x, "[")
}
#' @export
`[<-.vctrs_sclr` <- function(x, ..., value) {
stop_unsupported(x, "[<-")
}
#' @export
c.vctrs_sclr <- function(...) {
stop_unsupported(..1, "c")
}
#' @export
Math.vctrs_sclr <- function(x, ...) {
stop_unsupported(x, .Generic)
}
#' @export
Ops.vctrs_sclr <- function(e1, e2) {
stop_unsupported(e1, .Generic)
}
#' @export
Complex.vctrs_sclr <- function(z) {
stop_unsupported(z, .Generic)
}
#' @export
Summary.vctrs_sclr <- function(..., na.rm = TRUE) {
stop_unsupported(..1, .Generic)
}
#' @export
`names<-.vctrs_sclr` <- function(x, value) {
stop_unsupported(x, "names<-")
}
#' @export
xtfrm.vctrs_sclr <- function(x) {
stop_unsupported(x, "xtfrm")
}
#' @export
`dim<-.vctrs_sclr` <- function(x, value) {
stop_unsupported(x, "dim<-")
}
#' @export
`dimnames<-.vctrs_sclr` <- function(x, value) {
stop_unsupported(x, "dimnames<-")
}
#' @export
levels.vctrs_sclr <- function(x) {
stop_unsupported(x, "levels")
}
#' @export
`levels<-.vctrs_sclr` <- function(x, value) {
stop_unsupported(x, "levels<-")
}
#' @export
`t.vctrs_sclr` <- function(x) {
stop_unsupported(x, "t")
}
#' @export
`is.na<-.vctrs_sclr` <- function(x, value) {
stop_unsupported(x, "is.na<-")
}
#' @export
unique.vctrs_sclr <- function(x, incomparables = FALSE, ...) {
stop_unsupported(x, "unique")
}
#' @export
duplicated.vctrs_sclr <- function(x, incomparables = FALSE, ...) {
stop_unsupported(x, "unique")
}
#' @export
anyDuplicated.vctrs_sclr <- function(x, incomparables = FALSE, ...) {
stop_unsupported(x, "unique")
}
#' @export
as.logical.vctrs_sclr <- function(x, ...) {
stop_unsupported(x, "as.logical")
}
#' @export
as.integer.vctrs_sclr <- function(x, ...) {
stop_unsupported(x, "as.integer")
}
#' @export
as.double.vctrs_sclr <- function(x, ...) {
stop_unsupported(x, "as.double")
}
#' @export
as.character.vctrs_sclr <- function(x, ...) {
stop_unsupported(x, "as.character")
}
#' @export
as.Date.vctrs_sclr <- function(x, ...) {
stop_unsupported(x, "as.Date")
}
#' @export
as.POSIXct.vctrs_sclr <- function(x, tz = "", ...) {
stop_unsupported(x, "as.POSIXct")
}
# Unimplemented -----------------------------------------------------------
#' @export
summary.vctrs_sclr <- function(object, ...) {
# nocov start
stop_unimplemented(object, "summary")
# nocov end
}
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/type-sclr.R
|
# Imported at load-time in `sf_env`
st_crs = function(...) stop_sf()
st_precision = function(...) stop_sf()
st_as_sf = function(...) stop_sf()
stop_sf = function() abort("Internal error: Failed sf import.")
sf_deps = c(
"st_crs",
"st_precision",
"st_as_sf"
)
sf_env = env()
# sf namespace
local(envir = sf_env, {
# Registered at load-time (same for all other methods)
vec_proxy_sf = function(x, ...) {
x
}
vec_restore_sf = function(x, to, ...) {
sfc_name = attr(to, "sf_column")
crs = st_crs(to)
prec = st_precision(to)
st_as_sf(
x,
sf_column_name = sfc_name,
crs = crs,
precision = prec,
stringsAsFactors = FALSE
)
}
sf_ptype2 = function(x, y, ...) {
data = vctrs::df_ptype2(x, y, ...)
# Workaround for `c()` fallback sentinels. Must be fixed before
# moving the methods downstream.
opts <- match_fallback_opts(...)
if (identical(opts$s3_fallback, S3_FALLBACK_true)) {
return(data)
}
x_sf <- inherits(x, "sf")
y_sf <- inherits(y, "sf")
if (x_sf && y_sf) {
# Take active geometry from left-hand side
sfc_name = attr(x, "sf_column")
# CRS and precision must match
crs = common_crs(x, y)
prec = common_prec(x, y)
} else if (x_sf) {
sfc_name = attr(x, "sf_column")
crs = st_crs(x)
prec = st_precision(x)
} else if (y_sf) {
sfc_name = attr(y, "sf_column")
crs = st_crs(y)
prec = st_precision(y)
} else {
stop("Internal error: Expected at least one `sf` input.")
}
st_as_sf(
data,
sf_column_name = sfc_name,
crs = crs,
precision = prec,
stringsAsFactors = FALSE
)
}
vec_ptype2_sf_sf = function(x, y, ...) {
sf_ptype2(x, y, ...)
}
vec_ptype2_sf_data.frame = function(x, y, ...) {
sf_ptype2(x, y, ...)
}
vec_ptype2_data.frame_sf = function(x, y, ...) {
sf_ptype2(x, y, ...)
}
# Maybe we should not have these methods, but they are currently
# required to avoid the base-df fallback
vec_ptype2_sf_tbl_df = function(x, y, ...) {
new_data_frame(sf_ptype2(x, y, ...))
}
vec_ptype2_tbl_df_sf = function(x, y, ...) {
new_data_frame(sf_ptype2(x, y, ...))
}
sf_cast = function(x, to, ...) {
data = vctrs::df_cast(x, to, ...)
# Workaround for `c()` fallback sentinels. Must be fixed before
# moving the methods downstream.
opts <- match_fallback_opts(...)
if (identical(opts$s3_fallback, S3_FALLBACK_true)) {
return(data)
}
sfc_name = attr(to, "sf_column")
crs = st_crs(to)
prec = st_precision(to)
st_as_sf(
data,
sf_column_name = sfc_name,
crs = crs,
precision = prec,
stringsAsFactors = FALSE
)
}
vec_cast_sf_sf = function(x, to, ...) {
sf_cast(x, to, ...)
}
vec_cast_sf_data.frame = function(x, to, ...) {
sf_cast(x, to, ...)
}
vec_cast_data.frame_sf = function(x, to, ...) {
df_cast(x, to, ...)
}
vec_proxy_order_sfc <- function(x, ...) {
# These are list columns, so they need to use the order-by-appearance proxy
# that is defined by `vec_proxy_order.list()`
x <- unstructure(x)
vec_proxy_order(x)
}
# take conservative approach of requiring equal CRS and precision
common_crs = function(x, y) {
lhs = st_crs(x)
rhs = st_crs(y)
if (lhs != rhs)
stop("coordinate reference systems not equal: use st_transform() first?")
lhs
}
common_prec = function(x, y) {
lhs = st_precision(x)
rhs = st_precision(y)
if (lhs != rhs)
stop("precisions not equal")
lhs
}
}) # local(envir = sf_env)
env_bind(ns_env("vctrs"), !!!as.list(sf_env))
# Local Variables:
# indent-tabs-mode: t
# ess-indent-offset: 4
# tab-width: 4
# End:
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/type-sf.R
|
#' Table S3 class
#'
#' These functions help the base table class fit into the vctrs type system
#' by providing coercion and casting functions.
#'
#' @keywords internal
#' @name table
NULL
#' @export
vec_restore.table <- function(x, to, ...) {
new_table(x, dim = dim(x), dimnames = dimnames(x))
}
# Print -------------------------------------------------------------------
#' @export
vec_ptype_full.table <- function(x, ...) {
paste0("table", vec_ptype_shape(x))
}
#' @export
vec_ptype_abbr.table <- function(x, ...) {
"table"
}
# Coercion ----------------------------------------------------------------
#' @export
vec_ptype2.table.table <- function(x, y, ..., x_arg = "", y_arg = "") {
ptype <- vec_ptype2(unstructure(x), unstructure(y))
vec_shaped_ptype(new_table(ptype), x, y, x_arg = x_arg, y_arg = y_arg)
}
#' @export
vec_cast.table.table <- function(x, to, ...) {
out <- vec_cast(unstructure(x), unstructure(to))
out <- new_table(out, dim = dim(x), dimnames = dimnames(x))
shape_broadcast(out, to, ...)
}
# ------------------------------------------------------------------------------
new_table <- function(x = integer(), dim = NULL, dimnames = NULL) {
if (is_null(dim)) {
dim <- length(x)
} else if (!is.integer(dim)) {
abort("`dim` must be an integer vector.")
}
n_elements <- prod(dim)
n_x <- length(x)
if (n_elements != n_x) {
abort(glue::glue(
"Length implied by `dim`, {n_elements}, must match the length of `x`, {n_x}."
))
}
structure(x, dim = dim, dimnames = dimnames, class = "table")
}
is_bare_table <- function(x) {
identical(class(x), "table")
}
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/type-table.R
|
#' @rdname df_ptype2
#' @export
tib_ptype2 <- function(x,
y,
...,
x_arg = "",
y_arg = "",
call = caller_env()) {
.Call(
ffi_tib_ptype2,
x = x,
y = y,
x_arg = x_arg,
y_arg = y_arg,
frame = environment()
)
}
#' @rdname df_ptype2
#' @export
tib_cast <- function(x,
to,
...,
x_arg = "",
to_arg = "",
call = caller_env()) {
.Call(
ffi_tib_cast,
x = x,
to = to,
x_arg = x_arg,
to_arg = to_arg,
frame = environment()
)
}
df_as_tibble <- function(df) {
class(df) <- c("tbl_df", "tbl", "data.frame")
df
}
# Conditionally registered in .onLoad()
vec_ptype2_tbl_df_tbl_df <- function(x, y, ...) {
vec_ptype2_dispatch_native(x, y, ...)
}
vec_ptype2_tbl_df_data.frame <- function(x, y, ...) {
vec_ptype2_dispatch_native(x, y, ...)
}
vec_ptype2_data.frame_tbl_df <- function(x, y, ...) {
vec_ptype2_dispatch_native(x, y, ...)
}
vec_cast_tbl_df_tbl_df <- function(x, to, ...) {
vec_cast_dispatch_native(x, to, ...)
}
vec_cast_data.frame_tbl_df <- function(x, to, ...) {
vec_cast_dispatch_native(x, to, ...)
}
vec_cast_tbl_df_data.frame <- function(x, to, ...) {
vec_cast_dispatch_native(x, to, ...)
}
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/type-tibble.R
|
#' A 1d vector of unspecified type
#'
#' This is a [partial type][new_partial] used to represent logical vectors
#' that only contain `NA`. These require special handling because we want to
#' allow `NA` to specify missingness without requiring a type.
#'
#' @keywords internal
#' @param n Length of vector
#' @export
#' @examples
#' vec_ptype_show()
#' vec_ptype_show(NA)
#'
#' vec_c(NA, factor("x"))
#' vec_c(NA, Sys.Date())
#' vec_c(NA, Sys.time())
#' vec_c(NA, list(1:3, 4:5))
unspecified <- function(n = 0) {
.Call(vctrs_unspecified, n)
}
#' @export
`[.vctrs_unspecified` <- function(x, i, ...) {
unspecified(length(NextMethod()))
}
#' @export
print.vctrs_unspecified <- function(x, ...) {
cat("<unspecified> [", length(x), "]\n", sep = "")
}
#' @export
vec_ptype_abbr.vctrs_unspecified <- function(x, ...) {
"???"
}
is_unspecified <- function(x) {
.Call(vctrs_is_unspecified, x)
}
ununspecify <- function(x) {
if (is_unspecified(x)) {
new_logical(length(x))
} else {
x
}
}
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/type-unspecified.R
|
#' vctr (vector) S3 class
#'
#' @description
#' This abstract class provides a set of useful default methods that makes it
#' considerably easier to get started with a new S3 vector class. See
#' `vignette("s3-vector")` to learn how to use it to create your own S3
#' vector classes.
#'
#' @details
#' List vctrs are special cases. When created through `new_vctr()`, the
#' resulting list vctr should always be recognized as a list by
#' `obj_is_list()`. Because of this, if `inherit_base_type` is `FALSE`
#' an error is thrown.
#'
#' @section Base methods:
#' The vctr class provides methods for many base generics using a smaller
#' set of generics defined by this package. Generally, you should think
#' carefully before overriding any of the methods that vctrs implements for
#' you as they've been carefully planned to be internally consistent.
#'
#' * `[[` and `[` use `NextMethod()` dispatch to the underlying base function,
#' then restore attributes with `vec_restore()`.
#' `rep()` and `length<-` work similarly.
#'
#' * `[[<-` and `[<-` cast `value` to same type as `x`, then call
#' `NextMethod()`.
#'
#' * `as.logical()`, `as.integer()`, `as.numeric()`, `as.character()`,
#' `as.Date()` and `as.POSIXct()` methods call `vec_cast()`.
#' The `as.list()` method calls `[[` repeatedly, and the `as.data.frame()`
#' method uses a standard technique to wrap a vector in a data frame.
#'
#' * `as.factor()`, `as.ordered()` and `as.difftime()` are not generic functions
#' in base R, but have been reimplemented as generics in the `generics`
#' package. `vctrs` extends these and calls `vec_cast()`. To inherit this
#' behaviour in a package, import and re-export the generic of interest
#' from `generics`.
#'
#' * `==`, `!=`, `unique()`, `anyDuplicated()`, and `is.na()` use
#' [vec_proxy()].
#'
#' * `<`, `<=`, `>=`, `>`, `min()`, `max()`, `range()`, `median()`,
#' `quantile()`, and `xtfrm()` methods use [vec_proxy_compare()].
#'
#' * `+`, `-`, `/`, `*`, `^`, `%%`, `%/%`, `!`, `&`, and `|` operators
#' use [vec_arith()].
#'
#' * Mathematical operations including the Summary group generics (`prod()`,
#' `sum()`, `any()`, `all()`), the Math group generics (`abs()`, `sign()`,
#' etc), `mean()`, `is.nan()`, `is.finite()`, and `is.infinite()`
#' use [vec_math()].
#'
#' * `dims()`, `dims<-`, `dimnames()`, `dimnames<-`, `levels()`, and
#' `levels<-` methods throw errors.
#'
#' @param .data Foundation of class. Must be a vector
#' @param ... Name-value pairs defining attributes
#' @param class Name of subclass.
#' @param inherit_base_type `r lifecycle::badge("experimental")`
#' A single logical, or `NULL`. Does this class extend the base type of
#' `.data`? i.e. does the resulting object extend the behaviour of the
#' underlying type? Defaults to `FALSE` for all types except lists, which
#' are required to inherit from the base type.
#' @export
#' @keywords internal
#' @aliases vctr
new_vctr <- function(.data,
...,
class = character(),
inherit_base_type = NULL) {
if (!is_vector(.data)) {
abort("`.data` must be a vector type.")
}
if (is_list(.data)) {
if (is.data.frame(.data)) {
abort("`.data` can't be a data frame.")
}
if (is.null(inherit_base_type)) {
inherit_base_type <- TRUE
} else if (is_false(inherit_base_type)) {
abort("List `.data` must inherit from the base type.")
}
}
# Default to `FALSE` in all cases except lists
if (is.null(inherit_base_type)) {
inherit_base_type <- FALSE
}
names <- names(.data)
names <- names_repair_missing(names)
class <- c(class, "vctrs_vctr", if (inherit_base_type) typeof(.data))
attrib <- list(names = names, ..., class = class)
vec_set_attributes(.data, attrib)
}
names_repair_missing <- function(x) {
if (is.null(x)) {
return(x)
}
if (vec_any_missing(x)) {
# We never want to allow `NA_character_` names to slip through, but
# erroring on them has caused issues. Instead, we repair them to the
# empty string (#784).
missing <- vec_detect_missing(x)
x <- vec_assign(x, missing, "")
}
x
}
#' @export
vec_proxy.vctrs_vctr <- function(x, ...) {
if (is_list(x)) {
unclass(x)
} else {
x
}
}
#' @export
vec_restore.vctrs_vctr <- function(x, to, ..., i = NULL) {
if (typeof(x) != typeof(to)) {
stop_incompatible_cast(x, to, x_arg = "", to_arg = "")
}
NextMethod()
}
#' @method vec_cast vctrs_vctr
#' @export
vec_cast.vctrs_vctr <- function(x, to, ...) {
UseMethod("vec_cast.vctrs_vctr")
}
vctr_cast <- function(x,
to,
...,
x_arg = "",
to_arg = "",
call = caller_env()) {
# These are not strictly necessary, but make bootstrapping a new class
# a bit simpler
if (is.object(x)) {
if (is_same_type(x, to)) {
x
} else {
stop_incompatible_cast(
x,
to,
x_arg = x_arg,
to_arg = to_arg,
call = call
)
}
} else {
# FIXME: `vec_restore()` should only be called on proxies
vec_restore(x, to)
}
}
#' @export
c.vctrs_vctr <- function(..., recursive = FALSE, use.names = TRUE) {
if (!is_false(recursive)) {
abort("`recursive` must be `FALSE` when concatenating vctrs classes.")
}
if (!is_true(use.names)) {
abort("`use.names` must be `TRUE` when concatenating vctrs classes.")
}
vec_c(...)
}
# Printing ----------------------------------------------------------------
#' @export
print.vctrs_vctr <- function(x, ...) {
obj_print(x, ...)
invisible(x)
}
#' @export
str.vctrs_vctr <- function(object, ...) {
obj_str(object, ...)
}
#' @export
format.vctrs_vctr <- function(x, ...) {
format(vec_data(x), ...)
}
# Subsetting --------------------------------------------------------------
#' @export
`[.vctrs_vctr` <- function(x, i, ...) {
vec_index(x, i, ...)
}
#' @export
`[[.vctrs_vctr` <- function(x, i, ...) {
if (is.list(x)) {
NextMethod()
} else {
vec_restore(NextMethod(), x)
}
}
#' @export
`$.vctrs_vctr` <- function(x, i) {
if (is.list(x)) {
NextMethod()
} else {
vec_restore(NextMethod(), x)
}
}
#' @export
rep.vctrs_vctr <- function(x, ...) {
vec_restore(NextMethod(), x)
}
#' @export
`length<-.vctrs_vctr` <- function(x, value) {
vec_restore(NextMethod(), x)
}
#' @export
diff.vctrs_vctr <- function(x, lag = 1L, differences = 1L, ...) {
stopifnot(length(lag) == 1L, lag >= 1L)
stopifnot(length(differences) == 1L, differences >= 1L)
n <- vec_size(x)
if (lag * differences >= n)
return(vec_slice(x, 0L))
out <- x
for (i in seq_len(differences)) {
n <- vec_size(out)
lhs <- (1L + lag):n
rhs <- 1L:(n - lag)
out <- vec_slice(out, lhs) - vec_slice(out, rhs)
}
out
}
# Modification -------------------------------------------------------------
#' @export
`[[<-.vctrs_vctr` <- function(x, ..., value) {
if (!is.list(x)) {
value <- vec_cast(value, x)
}
NextMethod()
}
#' @export
`$<-.vctrs_vctr` <- function(x, i, value) {
if (is.list(x)) {
NextMethod()
} else {
# Default behaviour is to cast LHS to a list
abort("$ operator is invalid for atomic vectors.")
}
}
#' @export
`[<-.vctrs_vctr` <- function(x, i, value) {
value <- vec_cast(value, x)
NextMethod()
}
#' @export
`names<-.vctrs_vctr` <- function(x, value) {
if (length(value) != 0 && length(value) != length(x)) {
abort("`names()` must be the same length as x.")
}
value <- names_repair_missing(value)
NextMethod()
}
# Coercion ----------------------------------------------------------------
#' @export
as.logical.vctrs_vctr <- function(x, ...) {
vec_cast(x, logical())
}
#' @export
as.integer.vctrs_vctr <- function(x, ...) {
vec_cast(x, integer())
}
#' @export
as.double.vctrs_vctr <- function(x, ...) {
vec_cast(x, double())
}
#' @export
as.character.vctrs_vctr <- function(x, ...) {
vec_cast(x, character())
}
#' @export
as.list.vctrs_vctr <- function(x, ...) {
out <- vec_chop(x)
if (obj_is_list(x)) {
out <- lapply(out, `[[`, 1)
}
out
}
#' @export
as.Date.vctrs_vctr <- function(x, ...) {
vec_cast(x, new_date())
}
#' @export
as.POSIXct.vctrs_vctr <- function(x, tz = "", ...) {
vec_cast(x, new_datetime(tzone = tz))
}
#' @export
as.POSIXlt.vctrs_vctr <- function(x, tz = "", ...) {
to <- as.POSIXlt(new_datetime(), tz = tz)
vec_cast(x, to)
}
# Work around inconsistencies in as.data.frame()
as.data.frame2 <- function(x) {
# Unclass to avoid dispatching on `as.data.frame()` methods that break size
# invariants, like `as.data.frame.table()` (#913). This also prevents infinite
# recursion with shaped vctrs in `as.data.frame.vctrs_vctr()`.
x <- unclass(x)
out <- as.data.frame(x)
if (vec_dim_n(x) == 1) {
# 1D arrays are not stripped from their dimensions
out[[1]] <- as.vector(out[[1]])
# 1D arrays are auto-labelled with substitute()
names(out) <- "V1"
}
out
}
#' @export
as.data.frame.vctrs_vctr <- function(x,
row.names = NULL,
optional = FALSE,
...,
nm = paste(deparse(substitute(x), width.cutoff = 500L), collapse = " ")) {
force(nm)
if (has_dim(x)) {
return(as.data.frame2(x))
}
cols <- list(x)
if (!optional) {
names(cols) <- nm
}
new_data_frame(cols, n = vec_size(x))
}
# Dynamically registered in .onLoad()
as.factor.vctrs_vctr <- function(x, levels = character(), ...) {
vec_cast(x, new_factor(levels = levels))
}
# Dynamically registered in .onLoad()
as.ordered.vctrs_vctr <- function(x, levels = character(), ...) {
vec_cast(x, new_ordered(levels = levels))
}
# Dynamically registered in .onLoad()
as.difftime.vctrs_vctr <- function(x, units = "secs", ...) {
vec_cast(x, new_duration(units = units))
}
# Equality ----------------------------------------------------------------
#' @export
`==.vctrs_vctr` <- function(e1, e2) {
vec_equal(e1, e2)
}
#' @export
`!=.vctrs_vctr` <- function(e1, e2) {
!vec_equal(e1, e2)
}
#' @export
is.na.vctrs_vctr <- function(x) {
vec_detect_missing(x)
}
#' @importFrom stats na.fail
#' @export
na.fail.vctrs_vctr <- function(object, ...) {
if (vec_any_missing(object)) {
# Return the same error as `na.fail.default()`
abort("missing values in object")
}
object
}
#' @importFrom stats na.omit
#' @export
na.omit.vctrs_vctr <- function(object, ...) {
na_remove(object, "omit")
}
#' @importFrom stats na.exclude
#' @export
na.exclude.vctrs_vctr <- function(object, ...) {
na_remove(object, "exclude")
}
na_remove <- function(x, type) {
# The only difference between `na.omit()` and `na.exclude()` is the class
# of the `na.action` attribute
if (!vec_any_missing(x)) {
return(x)
}
# `na.omit/exclude()` attach the locations of the omitted values to the result
missing <- vec_detect_missing(x)
loc <- which(missing)
names <- vec_names(x)
if (!is_null(names)) {
# `na.omit/exclude()` retain the original names, if applicable
names <- vec_slice(names, loc)
loc <- vec_set_names(loc, names)
}
attr(loc, "class") <- type
out <- vec_slice(x, !missing)
attr(out, "na.action") <- loc
out
}
#' @export
anyNA.vctrs_vctr <- function(x, recursive = FALSE) {
if (recursive && obj_is_list(x)) {
any(map_lgl(x, anyNA, recursive = recursive))
} else {
any(is.na(x))
}
}
#' @export
unique.vctrs_vctr <- function(x, incomparables = FALSE, ...) {
vec_unique(x)
}
#' @export
duplicated.vctrs_vctr <- function(x, incomparables = FALSE, ...) {
vec_duplicate_id(x) != seq_along(x)
}
#' @export
anyDuplicated.vctrs_vctr <- function(x, incomparables = FALSE, ...) {
vec_duplicate_any(x)
}
# Comparison ----------------------------------------------------------------
#' @export
`<=.vctrs_vctr` <- function(e1, e2) {
vec_compare(e1, e2) <= 0
}
#' @export
`<.vctrs_vctr` <- function(e1, e2) {
vec_compare(e1, e2) < 0
}
#' @export
`>=.vctrs_vctr` <- function(e1, e2) {
vec_compare(e1, e2) >= 0
}
#' @export
`>.vctrs_vctr` <- function(e1, e2) {
vec_compare(e1, e2) > 0
}
#' @export
xtfrm.vctrs_vctr <- function(x) {
proxy <- vec_proxy_order(x)
type <- typeof(proxy)
if (type == "logical") {
proxy <- unstructure(proxy)
proxy <- as.integer(proxy)
return(proxy)
}
if (type %in% c("integer", "double")) {
proxy <- unstructure(proxy)
return(proxy)
}
vec_rank(proxy, ties = "dense", incomplete = "na")
}
#' @importFrom stats median
#' @export
median.vctrs_vctr <- function(x, ..., na.rm = FALSE) {
# nocov start
stop_unimplemented(x, "median")
# nocov end
}
#' @importFrom stats quantile
#' @export
quantile.vctrs_vctr <- function(x, ..., type = 1, na.rm = FALSE) {
# nocov start
stop_unimplemented(x, "quantile")
# nocov end
}
vec_cast_or_na <- function(x, to, ...) {
tryCatch(
vctrs_error_incompatible_type = function(...) vec_init(to, length(x)),
vec_cast(x, to)
)
}
#' @export
min.vctrs_vctr <- function(x, ..., na.rm = FALSE) {
if (vec_is_empty(x)) {
return(vec_cast_or_na(Inf, x))
}
# TODO: implement to do vec_arg_min()
rank <- xtfrm(x)
if (isTRUE(na.rm)) {
idx <- which.min(rank)
if (vec_is_empty(idx)) {
return(vec_cast_or_na(Inf, x))
}
} else {
idx <- which(vec_equal(rank, min(rank), na_equal = TRUE))
}
x[[idx[[1]]]]
}
#' @export
max.vctrs_vctr <- function(x, ..., na.rm = FALSE) {
if (vec_is_empty(x)) {
return(vec_cast_or_na(-Inf, x))
}
# TODO: implement to do vec_arg_max()
rank <- xtfrm(x)
if (isTRUE(na.rm)) {
idx <- which.max(rank)
if (vec_is_empty(idx)) {
return(vec_cast_or_na(-Inf, x))
}
} else {
idx <- which(vec_equal(rank, max(rank), na_equal = TRUE))
}
x[[idx[[1]]]]
}
#' @export
range.vctrs_vctr <- function(x, ..., na.rm = FALSE) {
if (vec_is_empty(x)) {
return(vec_cast_or_na(c(Inf, -Inf), x))
}
# Inline `min()` / `max()` to only call `xtfrm()` once
rank <- xtfrm(x)
if (isTRUE(na.rm)) {
idx_min <- which.min(rank)
idx_max <- which.max(rank)
if (vec_is_empty(idx_min) && vec_is_empty(idx_max)) {
return(vec_cast_or_na(c(Inf, -Inf), x))
}
} else {
idx_min <- which(vec_equal(rank, min(rank), na_equal = TRUE))
idx_max <- which(vec_equal(rank, max(rank), na_equal = TRUE))
}
c(x[[idx_min[[1]]]], x[[idx_max[[1]]]])
}
# Numeric -----------------------------------------------------------------
#' @export
Math.vctrs_vctr <- function(x, ...) {
vec_math(.Generic, x, ...)
}
#' @export
Summary.vctrs_vctr <- function(..., na.rm = FALSE) {
vec_math(.Generic, vec_c(...), na.rm = na.rm)
}
#' @export
mean.vctrs_vctr <- function(x, ..., na.rm = FALSE) {
vec_math("mean", x, na.rm = na.rm)
}
#' @export
is.finite.vctrs_vctr <- function(x) {
vec_math("is.finite", x)
}
#' @export
is.infinite.vctrs_vctr <- function(x) {
vec_math("is.infinite", x)
}
#' @export
is.nan.vctrs_vctr <- function(x) {
vec_math("is.nan", x)
}
# Arithmetic --------------------------------------------------------------
#' @export
`+.vctrs_vctr` <- function(e1, e2) {
if (missing(e2)) {
vec_arith("+", e1, MISSING())
} else {
vec_arith("+", e1, e2)
}
}
#' @export
`-.vctrs_vctr` <- function(e1, e2) {
if (missing(e2)) {
vec_arith("-", e1, MISSING())
} else {
vec_arith("-", e1, e2)
}
}
#' @export
`*.vctrs_vctr` <- function(e1, e2) {
vec_arith("*", e1, e2)
}
#' @export
`/.vctrs_vctr` <- function(e1, e2) {
vec_arith("/", e1, e2)
}
#' @export
`^.vctrs_vctr` <- function(e1, e2) {
vec_arith("^", e1, e2)
}
#' @export
`%%.vctrs_vctr` <- function(e1, e2) {
vec_arith("%%", e1, e2)
}
#' @export
`%/%.vctrs_vctr` <- function(e1, e2) {
vec_arith("%/%", e1, e2)
}
#' @export
`!.vctrs_vctr` <- function(x) {
vec_arith("!", x, MISSING())
}
#' @export
`&.vctrs_vctr` <- function(e1, e2) {
vec_arith("&", e1, e2)
}
#' @export
`|.vctrs_vctr` <- function(e1, e2) {
vec_arith("|", e1, e2)
}
# Unimplemented ------------------------------------------------------------
#' @export
summary.vctrs_vctr <- function(object, ...) {
# nocov start
stop_unimplemented(object, "summary")
# nocov end
}
# Unsupported --------------------------------------------------------------
#' @export
`dim<-.vctrs_vctr` <- function(x, value) {
stop_unsupported(x, "dim<-")
}
#' @export
`dimnames<-.vctrs_vctr` <- function(x, value) {
stop_unsupported(x, "dimnames<-")
}
#' @export
levels.vctrs_vctr <- function(x) {
NULL
}
#' @export
`levels<-.vctrs_vctr` <- function(x, value) {
stop_unsupported(x, "levels<-")
}
#' @export
`t.vctrs_vctr` <- function(x) {
stop_unsupported(x, "t")
}
#' @export
`is.na<-.vctrs_vctr` <- function(x, value) {
vec_assign(x, value, vec_init(x))
}
# Helpers -----------------------------------------------------------------
# This simple class is used for testing as defining methods inside
# a test does not work (because the lexical scope is lost)
# nocov start
new_hidden <- function(x = double()) {
stopifnot(is.numeric(x))
new_vctr(vec_cast(x, double()), class = "hidden", inherit_base_type = FALSE)
}
format.hidden <- function(x, ...) rep("xxx", length(x))
local_hidden <- function(frame = caller_env()) {
local_bindings(.env = global_env(), .frame = frame,
vec_ptype2.hidden.hidden = function(x, y, ...) new_hidden(),
vec_ptype2.hidden.double = function(x, y, ...) new_hidden(),
vec_ptype2.double.hidden = function(x, y, ...) new_hidden(),
vec_ptype2.hidden.logical = function(x, y, ...) new_hidden(),
vec_ptype2.logical.hidden = function(x, y, ...) new_hidden(),
vec_cast.hidden.hidden = function(x, to, ...) x,
vec_cast.hidden.double = function(x, to, ...) new_hidden(vec_data(x)),
vec_cast.double.hidden = function(x, to, ...) vec_data(x),
vec_cast.hidden.logical = function(x, to, ...) new_hidden(as.double(x)),
vec_cast.logical.hidden = function(x, to, ...) as.logical(vec_data(x))
)
}
# nocov end
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/type-vctr.R
|
#' Find the prototype of a set of vectors
#'
#' `vec_ptype()` returns the unfinalised prototype of a single vector.
#' `vec_ptype_common()` finds the common type of multiple vectors.
#' `vec_ptype_show()` nicely prints the common type of any number of
#' inputs, and is designed for interactive exploration.
#'
#' @inheritParams rlang::args_error_context
#'
#' @param x A vector
#' @param ... For `vec_ptype()`, these dots are for future extensions and must
#' be empty.
#'
#' For `vec_ptype_common()` and `vec_ptype_show()`, vector inputs.
#' @param x_arg Argument name for `x`. This is used in error messages to inform
#' the user about the locations of incompatible types.
#' @param .ptype If `NULL`, the default, the output type is determined by
#' computing the common type across all elements of `...`.
#'
#' Alternatively, you can supply `.ptype` to give the output known type.
#' If `getOption("vctrs.no_guessing")` is `TRUE` you must supply this value:
#' this is a convenient way to make production code demand fixed types.
#' @return `vec_ptype()` and `vec_ptype_common()` return a prototype
#' (a size-0 vector)
#'
#' @section `vec_ptype()`:
#' `vec_ptype()` returns [size][vec_size] 0 vectors potentially
#' containing attributes but no data. Generally, this is just
#' `vec_slice(x, 0L)`, but some inputs require special
#' handling.
#'
#' * While you can't slice `NULL`, the prototype of `NULL` is
#' itself. This is because we treat `NULL` as an identity value in
#' the `vec_ptype2()` monoid.
#'
#' * The prototype of logical vectors that only contain missing values
#' is the special [unspecified] type, which can be coerced to any
#' other 1d type. This allows bare `NA`s to represent missing values
#' for any 1d vector type.
#'
#' See [internal-faq-ptype2-identity] for more information about
#' identity values.
#'
#' `vec_ptype()` is a _performance_ generic. It is not necessary to implement it
#' because the default method will work for any vctrs type. However the default
#' method builds around other vctrs primitives like `vec_slice()` which incurs
#' performance costs. If your class has a static prototype, you might consider
#' implementing a custom `vec_ptype()` method that returns a constant. This will
#' improve the performance of your class in many cases ([common
#' type][vec_ptype2] imputation in particular).
#'
#' Because it may contain unspecified vectors, the prototype returned
#' by `vec_ptype()` is said to be __unfinalised__. Call
#' [vec_ptype_finalise()] to finalise it. Commonly you will need the
#' finalised prototype as returned by `vec_slice(x, 0L)`.
#'
#' @section `vec_ptype_common()`:
#' `vec_ptype_common()` first finds the prototype of each input, then
#' successively calls [vec_ptype2()] to find a common type. It returns
#' a [finalised][vec_ptype_finalise] prototype.
#'
#' @section Dependencies of `vec_ptype()`:
#' - [vec_slice()] for returning an empty slice
#'
#' @section Dependencies of `vec_ptype_common()`:
#' - [vec_ptype2()]
#' - [vec_ptype_finalise()]
#'
#' @export
#' @examples
#' # Unknown types ------------------------------------------
#' vec_ptype_show()
#' vec_ptype_show(NA)
#' vec_ptype_show(NULL)
#'
#' # Vectors ------------------------------------------------
#' vec_ptype_show(1:10)
#' vec_ptype_show(letters)
#' vec_ptype_show(TRUE)
#'
#' vec_ptype_show(Sys.Date())
#' vec_ptype_show(Sys.time())
#' vec_ptype_show(factor("a"))
#' vec_ptype_show(ordered("a"))
#'
#' # Matrices -----------------------------------------------
#' # The prototype of a matrix includes the number of columns
#' vec_ptype_show(array(1, dim = c(1, 2)))
#' vec_ptype_show(array("x", dim = c(1, 2)))
#'
#' # Data frames --------------------------------------------
#' # The prototype of a data frame includes the prototype of
#' # every column
#' vec_ptype_show(iris)
#'
#' # The prototype of multiple data frames includes the prototype
#' # of every column that in any data frame
#' vec_ptype_show(
#' data.frame(x = TRUE),
#' data.frame(y = 2),
#' data.frame(z = "a")
#' )
vec_ptype <- function(x, ..., x_arg = "", call = caller_env()) {
check_dots_empty0(...)
return(.Call(ffi_ptype, x, x_arg, environment()))
UseMethod("vec_ptype")
}
#' @export
#' @rdname vec_ptype
vec_ptype_common <- function(...,
.ptype = NULL,
.arg = "",
.call = caller_env()) {
.External2(ffi_ptype_common, .ptype)
}
vec_ptype_common_opts <- function(...,
.ptype = NULL,
.opts = fallback_opts(),
.call = caller_env()) {
.External2(ffi_ptype_common_opts, .ptype, .opts)
}
vec_ptype_common_params <- function(...,
.ptype = NULL,
.s3_fallback = NULL,
.call = caller_env()) {
opts <- fallback_opts(
s3_fallback = .s3_fallback
)
vec_ptype_common_opts(
...,
.ptype = .ptype,
.opts = opts,
.call = .call
)
}
vec_ptype_common_fallback <- function(...,
.ptype = NULL,
.call = caller_env()) {
vec_ptype_common_opts(
...,
.ptype = .ptype,
.opts = full_fallback_opts(),
.call = .call
)
}
#' @export
#' @rdname vec_ptype
vec_ptype_show <- function(...) {
args <- compact(list2(...))
n <- length(args)
if (n == 0) {
cat_line("Prototype: NULL")
} else if (n == 1) {
cat_line("Prototype: ", vec_ptype_full(args[[1]]))
} else {
in_types <- map(args, vec_ptype)
out_types <- vector("list", length(in_types))
out_types[[1]] <- in_types[[1]]
for (i in seq2(2, n)) {
out_types[[i]] <- vec_ptype2(out_types[[i - 1]], in_types[[i]])
}
in_full <- paste0("<", map_chr(in_types, vec_ptype_full), ">")
out_full <- paste0("<", map_chr(out_types, vec_ptype_full), ">")
out <- cbind(
n = paste0(seq(0, n - 1), ". "),
lhs = c("", out_full[-n]),
comma = " , ",
rhs = in_full,
equals = " = ",
res = c(in_full[[1]], out_full[-1])
)
out <- t(apply(out, 1, pad_height))
out <- apply(out, 2, pad_width)
out[, "lhs"] <- parens(out[, "lhs"])
out[, "rhs"] <- parens(out[, "rhs"], FALSE)
lines <- strsplit(out, "\n")
dim(lines) <- dim(out)
steps <- apply(lines, 1, function(x) do.call(cbind, x))
if (is.list(steps)) {
step_lines <- unlist(lapply(steps, function(x) apply(x, 1, paste0, collapse = "")))
} else {
step_lines <- apply(steps, 2, paste0, collapse = "")
}
cat_line("Prototype: ", out_full[[n]])
cat_line(step_lines)
}
invisible()
}
vec_typeof <- function(x) {
.Call(vctrs_typeof, x, TRUE)
}
vec_typeof_bare <- function(x) {
.Call(vctrs_typeof, x, FALSE)
}
vec_type_info <- function(x) {
.Call(ffi_type_info, x)
}
vec_proxy_info <- function(x) {
.Call(ffi_proxy_info, x)
}
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/type.R
|
#' Find the common type for a pair of vectors
#'
#' @description
#'
#' `vec_ptype2()` defines the coercion hierarchy for a set of related
#' vector types. Along with [vec_cast()], this generic forms the
#' foundation of type coercions in vctrs.
#'
#' `vec_ptype2()` is relevant when you are implementing vctrs methods
#' for your class, but it should not usually be called directly. If
#' you need to find the common type of a set of inputs, call
#' [vec_ptype_common()] instead. This function supports multiple
#' inputs and [finalises][vec_ptype_finalise] the common type.
#'
#' @includeRmd man/faq/developer/links-coercion.Rmd
#'
#' @inheritParams rlang::args_dots_empty
#' @inheritParams rlang::args_error_context
#' @param x,y Vector types.
#' @param x_arg,y_arg Argument names for `x` and `y`. These are used
#' in error messages to inform the user about the locations of
#' incompatible types (see [stop_incompatible_type()]).
#'
#' @seealso [stop_incompatible_type()] when you determine from the
#' attributes that an input can't be cast to the target type.
#'
#' @section Dependencies:
#' - [vec_ptype()] is applied to `x` and `y`
#'
#' @export
vec_ptype2 <- function(x,
y,
...,
x_arg = caller_arg(x),
y_arg = caller_arg(y),
call = caller_env()) {
if (!missing(...)) {
check_ptype2_dots_empty(...)
return(vec_ptype2_opts(
x,
y,
opts = match_fallback_opts(...),
x_arg = x_arg,
y_arg = y_arg,
call = call
))
}
return(.Call(ffi_ptype2, x, y, environment()))
UseMethod("vec_ptype2")
}
vec_ptype2_dispatch_s3 <- function(x,
y,
...,
x_arg = "",
y_arg = "",
call = caller_env()) {
UseMethod("vec_ptype2")
}
vec_ptype2_dispatch_native <- function(x,
y,
...,
x_arg = "",
y_arg = "",
call = caller_env()) {
fallback_opts <- match_fallback_opts(...)
.Call(
ffi_ptype2_dispatch_native,
x,
y,
fallback_opts,
frame = environment()
)
}
#' Default cast and ptype2 methods
#'
#' @description
#'
#' These functions are automatically called when no [vec_ptype2()] or
#' [vec_cast()] method is implemented for a pair of types.
#'
#' * They apply special handling if one of the inputs is of type
#' `AsIs` or `sfc`.
#'
#' * They attempt a number of fallbacks in cases where it would be too
#' inconvenient to be strict:
#'
#' - If the class and attributes are the same they are considered
#' compatible. `vec_default_cast()` returns `x` in this case.
#'
#' - In case of incompatible data frame classes, they fall back to
#' `data.frame`. If an incompatible subclass of tibble is
#' involved, they fall back to `tbl_df`.
#'
#' * Otherwise, an error is thrown with [stop_incompatible_type()] or
#' [stop_incompatible_cast()].
#'
#' @keywords internal
#' @export
vec_default_ptype2 <- function(x,
y,
...,
x_arg = "",
y_arg = "",
call = caller_env()) {
if (is_asis(x)) {
return(vec_ptype2_asis_left(
x,
y,
x_arg = x_arg,
y_arg = y_arg,
call = call
))
}
if (is_asis(y)) {
return(vec_ptype2_asis_right(
x,
y,
x_arg = x_arg,
y_arg = y_arg,
call = call
))
}
opts <- match_fallback_opts(...)
if (opts$s3_fallback && can_fall_back_2(x, y)) {
common <- common_class_suffix(x, y)
if (length(common)) {
return(new_common_class_fallback(x, common))
}
}
if (is.data.frame(x) && is.data.frame(y)) {
out <- vec_ptype2_df_fallback(
x,
y,
opts,
x_arg = x_arg,
y_arg = y_arg,
call = call
)
if (identical(non_df_attrib(x), non_df_attrib(y))) {
attributes(out) <- c(df_attrib(out), non_df_attrib(x))
}
return(out)
}
if (is_same_type(x, y)) {
return(vec_ptype(x, x_arg = x_arg))
}
# The from-dispatch parameter is set only when called from our S3
# dispatch mechanism, when no method is found to dispatch to. It
# indicates whether the error message should provide advice about
# diverging attributes.
withRestarts(
stop_incompatible_type(
x,
y,
x_arg = x_arg,
y_arg = y_arg,
`vctrs:::from_dispatch` = match_from_dispatch(...),
call = call
),
vctrs_restart_ptype2 = function(ptype) {
ptype
}
)
}
# This wrapper for `stop_incompatible_type()` matches error context
# arguments. It is useful to pass ptype2 arguments through dots
# without risking unknown arguments getting stored as condition fields.
vec_incompatible_ptype2 <- function(x,
y,
...,
x_arg = "",
y_arg = "",
call = caller_env()) {
stop_incompatible_type(
x,
y,
x_arg = x_arg,
y_arg = y_arg,
call = call
)
}
# We can't check for a proxy or ptype2 method to determine whether a
# class is foreign, because we implement these generics for many base
# classes and we still need to allow base fallbacks with subclasses.
can_fall_back_2 <- function(x, y) {
if (!identical(typeof(x), typeof(y))) {
return(FALSE)
}
if (!can_fall_back(x) || !can_fall_back(y)) {
return(FALSE)
}
TRUE
}
can_fall_back <- function(x) {
UseMethod("can_fall_back")
}
#' @export
can_fall_back.vctrs_vctr <- function(x) {
# Work around bad interaction when `c()` method calls back into `vec_c()`
FALSE
}
#' @export
can_fall_back.ts <- function(x) {
# Work around bug with hard-coded `tsp` attribute in Rf_setAttrib()
FALSE
}
#' @export
can_fall_back.data.frame <- function(x) {
# The `c()` fallback is only for 1D vectors
FALSE
}
#' @export
`can_fall_back.vctrs:::common_class_fallback` <- function(x) {
TRUE
}
#' @export
can_fall_back.default <- function(x) {
# Don't fall back for classes that directly implement a proxy.
#
# NOTE: That's suboptimal. For instance this forces us to override
# `can_fall_back()` for `vctrs_vctr` to avoid recursing into
# `vec_c()` through `c()`. Maybe we want to avoid falling back for
# any vector that inherits a `vec_proxy()` method implemented
# _outside_ of vctrs, i.e. not for a base class?
is_null(s3_get_method(class(x)[[1]], "vec_proxy", ns = "vctrs"))
}
new_common_class_fallback <- function(x, fallback_class) {
structure(
vec_ptype(x),
class = "vctrs:::common_class_fallback",
fallback_class = fallback_class
)
}
#' @export
`vec_proxy.vctrs:::common_class_fallback` <- function(x, ...) {
x
}
is_common_class_fallback <- function(x) {
inherits(x, "vctrs:::common_class_fallback")
}
common_class_suffix <- function(x, y) {
vec_common_suffix(fallback_class(x), fallback_class(y))
}
fallback_class <- function(x) {
if (is_common_class_fallback(x)) {
attr(x, "fallback_class")
} else {
class(x)
}
}
check_ptype2_dots_empty <- function(...,
`vctrs:::from_dispatch`,
`vctrs:::s3_fallback`) {
check_dots_empty0(...)
}
match_fallback_opts <- function(..., `vctrs:::s3_fallback` = NULL) {
fallback_opts(
s3_fallback = `vctrs:::s3_fallback`
)
}
match_from_dispatch <- function(..., `vctrs:::from_dispatch` = FALSE) {
`vctrs:::from_dispatch`
}
fallback_opts <- function(s3_fallback = NULL) {
# Order is important for the C side
list(
s3_fallback = s3_fallback %||% s3_fallback_default()
)
}
full_fallback_opts <- function() {
fallback_opts(
s3_fallback = S3_FALLBACK_true
)
}
vec_ptype2_opts <- function(x,
y,
...,
opts,
x_arg = "",
y_arg = "",
call = caller_env()) {
.Call(ffi_ptype2_opts, x, y, opts, environment())
}
vec_ptype2_params <- function(x,
y,
...,
s3_fallback = NULL,
x_arg = "",
y_arg = "",
call = caller_env()) {
opts <- fallback_opts(
s3_fallback = s3_fallback
)
vec_ptype2_opts(
x,
y,
opts = opts,
x_arg = x_arg,
y_arg = y_arg,
call = call
)
}
vec_ptype2_no_fallback <- function(x,
y,
...,
x_arg = "",
y_arg = "",
call = caller_env()) {
opts <- fallback_opts(
s3_fallback = S3_FALLBACK_false
)
vec_ptype2_opts(
x,
y,
...,
,
opts = opts,
x_arg = x_arg,
y_arg = y_arg,
call = call
)
}
s3_fallback_default <- function() 0L
S3_FALLBACK_false <- 0L
S3_FALLBACK_true <- 1L
vec_typeof2 <- function(x, y) {
.Call(ffi_typeof2, x, y)
}
vec_typeof2_s3 <- function(x, y) {
.Call(ffi_typeof2_s3, x, y)
}
# https://github.com/r-lib/vctrs/issues/571
vec_is_coercible <- function(x,
y,
...,
opts = fallback_opts(),
x_arg = "",
y_arg = "",
call = caller_env()) {
check_dots_empty0(...)
.Call(
ffi_is_coercible,
x,
y,
opts,
environment()
)
}
vec_is_subtype <- function(x, super, ..., x_arg = "", super_arg = "") {
tryCatch(
vctrs_error_incompatible_type = function(...) FALSE,
{
common <- vctrs::vec_ptype2(x, super, ..., x_arg = x_arg, y_arg = super_arg)
vec_is(common, super)
}
)
}
vec_implements_ptype2 <- function(x) {
.Call(vctrs_implements_ptype2, x)
}
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/type2.R
|
parens <- function(x, left = TRUE) {
x_lines <- strsplit(x, "\n")
x_lines <- map(x_lines, paren, left = left)
map_chr(x_lines, paste0, collapse = "\n")
}
paren <- function(x, left = TRUE) {
if (length(x) <= 1) {
if (left) {
paste0("( ", x)
} else {
paste0(x, " )")
}
} else {
if (left) {
paste0(c("\u250c ", rep("\u2502 ", length(x) - 2), "\u2514 "), x)
} else {
paste0(format(x), c(" \u2510", rep(" \u2502", length(x) - 2), " \u2518"))
}
}
}
pad_height <- function(x) {
pad <- function(x, n) c(x, rep("", n - length(x)))
lines <- strsplit(x, "\n")
height <- max(map_int(lines, length))
lines <- map(lines, pad, height)
map_chr(lines, paste0, "\n", collapse = "")
}
pad_width <- function(x) {
lines <- strsplit(x, "\n", fixed = TRUE)
# fix up strsplit bug
n <- map_int(lines, length)
lines[n == 0] <- ""
width <- max(unlist(map(lines, nchar)))
lines <- map(lines, format, width = width)
map_chr(lines, paste, collapse = "\n")
}
str_backtick <- function(x) {
paste0("`", x, "`")
}
str_is_multiline <- function(x) {
grepl("\n", x)
}
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/utils-cli.R
|
str_dup <- function(x, times) {
paste0(rep(x, times = times), collapse = "")
}
indent <- function(x, n) {
pad <- str_dup(" ", n)
map_chr(x, gsub, pattern = "(\n+)", replacement = paste0("\\1", pad))
}
ones <- function(...) {
array(1, dim = c(...))
}
vec_coerce_bare <- function(x, type) {
# FIXME! Unexported wrapper around Rf_coerceVector()
coerce <- env_get(ns_env("rlang"), "vec_coerce")
coerce(x, type)
}
# Matches the semantics of c() - based on experimenting with the output
# of c(), not reading the source code.
outer_names <- function(names, outer, n) {
.Call(ffi_outer_names, names, outer, vec_cast(n, int()))
}
has_inner_names <- function(x) {
!all(map_lgl(map(x, vec_names), is.null))
}
cat_line <- function(...) {
cat(paste0(..., "\n", collapse = ""))
}
set_partition <- function(x, y) {
list(
both = intersect(x, y),
only_x = setdiff(x, y),
only_y = setdiff(y, x)
)
}
all_equal <- function(x) all(x == x[[1]])
inline_list <- function(title, x, width = getOption("width"), quote = "") {
label_width <- width - nchar(title)
x <- glue::glue_collapse(
encodeString(x, quote = quote),
sep = ", ",
width = label_width
)
paste0(title, x)
}
has_unique_names <- function(x) {
nms <- names(x)
if (length(nms) != length(x)) {
return(FALSE)
}
if (any(is.na(nms) | nms == "")) {
return(FALSE)
}
!anyDuplicated(nms)
}
compact <- function(x) {
is_null <- map_lgl(x, is.null)
x[!is_null]
}
paste_line <- function (...) {
paste(chr(...), collapse = "\n")
}
# Experimental
result <- function(ok = NULL, err = NULL) {
structure(
list(ok = ok, err = err),
class = "rlang_result"
)
}
result_get <- function(x) {
if (!is_null(x$err)) {
cnd_signal(x$err)
}
x$ok
}
obj_type <- function(x) {
if (vec_is(x)) {
vec_ptype_full(x)
} else if (is.object(x)) {
paste(class(x), collapse = "/")
} else if (is_function(x)) {
"function"
} else {
typeof(x)
}
}
new_opts <- function(x, opts, subclass = NULL, arg = NULL) {
if (!all(x %in% opts)) {
if (is_null(arg)) {
arg <- "Argument"
} else {
arg <- glue::glue("`{arg}`")
}
opts <- encodeString(opts, quote = "\"")
opts <- glue::glue_collapse(opts, sep = ", ", last = " or ")
abort(glue::glue("{arg} must be one of {opts}."))
}
structure(
set_names(opts %in% x, opts),
class = c(subclass, "vctrs_opts")
)
}
glue_data_bullets <- function(.data, ..., .env = caller_env()) {
glue_data <- function(...) glue::glue_data(.data, ..., .envir = .env)
format_error_bullets(map_chr(chr(...), glue_data))
}
unstructure <- function(x) {
attributes(x) <- NULL
x
}
# We almost never want `stringsAsFactors = TRUE`, and `FALSE` became
# the default in R 4.0.0. This wrapper ensures that our tests are compliant
# with versions of R before and after this change. Keeping it in `utils.R`
# rather than as a testthat helper ensures that it is sourced before any other
# testthat helpers.
data.frame <- function(..., stringsAsFactors = NULL) {
stringsAsFactors <- stringsAsFactors %||% FALSE
base::data.frame(..., stringsAsFactors = stringsAsFactors)
}
try_catch_callback <- function(data, cnd) {
.Call(vctrs_try_catch_callback, data, cnd)
}
try_catch_hnd <- function(data) {
function(cnd) {
try_catch_callback(data, cnd)
}
}
try_catch_impl <- function(data, ...) {
tryCatch(
try_catch_callback(data, NULL),
...
)
}
ns_methods <- function(name) {
ns_env(name)$.__S3MethodsTable__.
}
s3_find_method <- function(x, generic, ns = "base") {
stopifnot(
is_string(generic),
is_string(ns)
)
table <- ns_methods(ns_env(ns))
.Call(vctrs_s3_find_method, generic, x, table)
}
s3_get_method <- function(class, generic, ns = "base") {
stopifnot(
is_string(class),
is_string(generic),
is_string(ns)
)
table <- ns_methods(ns_env(ns))
.Call(ffi_s3_get_method, generic, class, table)
}
s3_method_specific <- function(x,
generic,
ns = "base",
default = TRUE) {
classes <- class(x)[[1]]
if (default) {
classes <- c(classes, "default")
}
for (class in classes) {
method <- s3_get_method(class, generic, ns = ns)
if (!is_null(method)) {
return(method)
}
}
cli::cli_abort("Can't find {.fn {generic}} method for {.cls {class}}.")
}
df_has_base_subset <- function(x) {
method <- s3_find_method(x, "[", ns = "base")
is_null(method) || identical(method, `[.data.frame`)
}
last <- function(x) {
x[[length(x)]]
}
# Find the longest common suffix of two vectors
vec_common_suffix <- function(x, y) {
common <- vec_cast_common(x = x, y = y)
x <- common$x
y <- common$y
x_size <- vec_size(x)
y_size <- vec_size(y)
n <- min(x_size, y_size)
if (!n) {
return(vec_slice(x, int()))
}
# Truncate the start of the vectors so they have equal size
if (x_size < y_size) {
y <- vec_slice(y, seq2(y_size - x_size + 1, y_size))
} else if (y_size < x_size) {
x <- vec_slice(x, seq2(x_size - y_size + 1, x_size))
}
# Find locations of unequal elements. Elements after the last
# location are the common suffix.
common <- vec_equal(x, y)
i <- which(!common)
# Slice the suffix after the last unequal element
if (length(i)) {
vec_slice(x, seq2(max(i) + 1, n))
} else {
x
}
}
import_from <- function(ns, names, env = caller_env()) {
objs <- env_get_list(ns_env(ns), names)
env_bind(env, !!!objs)
}
fast_c <- function(x, y) {
.Call(vctrs_fast_c, x, y)
}
# Based on r-lib/bench (itself based on gaborcsardi/prettyunits)
#' @export
format.vctrs_bytes <- function(x, scientific = FALSE, digits = 3, drop0trailing = TRUE, ...) {
nms <- names(x)
bytes <- unclass(x)
unit <- map_chr(x, find_unit, byte_units)
res <- round(bytes / byte_units[unit], digits = digits)
## Zero bytes
res[bytes == 0] <- 0
unit[bytes == 0] <- "B"
## NA and NaN bytes
res[is.na(bytes)] <- NA_real_
res[is.nan(bytes)] <- NaN
unit[is.na(bytes)] <- "" # Includes NaN as well
# Append an extra B to each unit
large_units <- unit %in% names(byte_units)[-1]
unit[large_units] <- paste0(unit[large_units], "B")
res <- format(res, scientific = scientific, digits = digits, drop0trailing = drop0trailing, ...)
stats::setNames(paste0(res, unit), nms)
}
#' @export
print.vctrs_bytes <- function(x, ...) {
print(format(x, ...), quote = FALSE)
}
tolerance <- sqrt(.Machine$double.eps)
find_unit <- function(x, units) {
if (is.na(x) || is.nan(x) || x <= 0 || is.infinite(x)) {
return(NA_character_)
}
epsilon <- 1 - (x * (1 / units))
names(utils::tail(n = 1, which(epsilon < tolerance)))
}
byte_units <- c(
'B' = 1,
'K' = 1024,
'M' = 1024 ^ 2,
'G' = 1024 ^ 3,
'T' = 1024 ^ 4,
'P' = 1024 ^ 5,
'E' = 1024 ^ 6,
'Z' = 1024 ^ 7,
'Y' = 1024 ^ 8
)
new_vctrs_bytes <- function(x) {
structure(x, class = c("vctrs_bytes", "numeric"))
}
named <- function(x) {
if (is_null(names(x))) {
names(x) <- names2(x)
}
x
}
browser <- function(...,
skipCalls = 0,
frame = parent.frame()) {
if (!identical(stdout(), getConnection(1))) {
sink(getConnection(1))
withr::defer(sink(), envir = frame)
}
# Calling `browser()` on exit avoids RStudio displaying the
# `browser2()` location. We still need one `n` to get to the
# expected place. Ideally `skipCalls` would not skip but exit the
# contexts.
on.exit(base::browser(..., skipCalls = skipCalls + 1))
}
vec_paste0 <- function(...) {
args <- vec_recycle_common(...)
exec(paste0, !!!args)
}
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/utils.R
|
#' Is a vector empty
#'
#' @description
#'
#' `r lifecycle::badge("defunct")`
#'
#' This function is defunct, please use [vec_is_empty()].
#'
#' @param x An object.
#'
#' @keywords internal
#' @export
vec_empty <- function(x) {
# Defunct: 2019-06
lifecycle::deprecate_stop(
when = "0.2.0",
what = "vec_empty()",
with = "vec_is_empty()"
)
}
#' Deprecated type functions
#'
#' @description
#'
#' `r lifecycle::badge("deprecated")`
#'
#' These functions have been renamed:
#'
#' * `vec_type()` => [vec_ptype()]
#' * `vec_type2()` => [vec_ptype2()]
#' * `vec_type_common()` => [vec_ptype_common()]
#'
#' @param x,y,...,.ptype Arguments for deprecated functions.
#'
#' @keywords internal
#' @export
vec_type <- function(x) {
# Deprecated: 2019-06
lifecycle::deprecate_warn(
when = "0.2.0",
what = "vec_type()",
with = "vec_ptype()",
always = TRUE
)
vec_ptype(x)
}
#' @rdname vec_type
#' @export
vec_type_common <- function(..., .ptype = NULL) {
# Deprecated: 2019-06
lifecycle::deprecate_warn(
when = "0.2.0",
what = "vec_type_common()",
with = "vec_ptype_common()",
always = TRUE
)
vec_ptype_common(..., .ptype = .ptype)
}
#' @rdname vec_type
#' @export
vec_type2 <- function(x, y, ...) {
# Deprecated: 2019-06
lifecycle::deprecate_warn(
when = "0.2.0",
what = "vec_type2()",
with = "vec_ptype2()",
always = TRUE
)
vec_ptype2(x, y, ...)
}
#' Convert to an index vector
#'
#' @description
#'
#' `r lifecycle::badge("deprecated")`
#'
#' `vec_as_index()` has been renamed to [vec_as_location()] and is
#' deprecated as of vctrs 0.2.2.
#'
#' @inheritParams vec_as_location
#'
#' @keywords internal
#' @export
vec_as_index <- function(i, n, names = NULL) {
# Soft-deprecated: 2020-01
lifecycle::deprecate_soft(
when = "0.2.2",
what = "vec_as_index()",
with = "vec_as_location()"
)
n <- vec_cast(n, integer())
vec_check_size(n, size = 1L)
i <- vec_as_subscript(i)
# Picked up from the environment at the C level
arg <- NULL
.Call(
ffi_as_location,
i = i,
n = n,
names = names,
loc_negative = "invert",
loc_oob = "error",
loc_zero = "remove",
missing = "propagate",
env = environment()
)
}
#' Expand the length of a vector
#'
#' @description
#' `r lifecycle::badge("deprecated")`
#'
#' `vec_repeat()` has been replaced with [vec_rep()] and [vec_rep_each()] and is
#' deprecated as of vctrs 0.3.0.
#'
#' @param x A vector.
#' @param each Number of times to repeat each element of `x`.
#' @param times Number of times to repeat the whole vector of `x`.
#' @return A vector the same type as `x` with size `vec_size(x) * times * each`.
#' @keywords internal
#' @export
vec_repeat <- function(x, each = 1L, times = 1L) {
# Soft-deprecated: 2020-03
lifecycle::deprecate_soft(
when = "0.3.0",
what = "vec_repeat()",
with = I("either `vec_rep()` or `vec_rep_each()`")
)
vec_check_size(each, size = 1L)
vec_check_size(times, size = 1L)
idx <- rep(vec_seq_along(x), times = times, each = each)
vec_slice(x, idx)
}
#' Chopping
#'
#' @description
#' `r lifecycle::badge("deprecated")`
#'
#' `vec_unchop()` has been renamed to [list_unchop()] and is deprecated as of
#' vctrs 0.5.0.
#'
#' @inheritParams list_unchop
#' @inherit list_unchop return
#'
#' @keywords internal
#' @export
vec_unchop <- function(x,
indices = NULL,
ptype = NULL,
name_spec = NULL,
name_repair = c("minimal", "unique", "check_unique", "universal")) {
# Soft-deprecated: 2022-09
lifecycle::deprecate_soft("0.5.0", "vec_unchop()", "list_unchop()")
list_unchop(
x = x,
indices = indices,
ptype = ptype,
name_spec = name_spec,
name_repair = name_repair
)
}
#' Missing values
#'
#' @description
#' `r lifecycle::badge("deprecated")`
#'
#' `vec_equal_na()` has been renamed to [vec_detect_missing()] and is deprecated
#' as of vctrs 0.5.0.
#'
#' @inheritParams vec_detect_missing
#'
#' @return
#' A logical vector the same size as `x`.
#'
#' @keywords internal
#' @export
vec_equal_na <- function(x) {
# Soft-deprecated: 2022-09
lifecycle::deprecate_soft("0.5.0", "vec_equal_na()", "vec_detect_missing()")
vec_detect_missing(x)
}
#' List checks
#'
#' @description
#' `r lifecycle::badge("deprecated")`
#'
#' These functions have been deprecated as of vctrs 0.6.0.
#'
#' - `vec_is_list()` has been renamed to [obj_is_list()].
#' - `vec_check_list()` has been renamed to [obj_check_list()].
#'
#' @inheritParams obj_is_list
#'
#' @keywords internal
#' @export
vec_is_list <- function(x) {
# Silently-deprecated: 2023-03
# lifecycle::deprecate_soft("0.6.0", "vec_is_list()", "obj_is_list()")
obj_is_list(x)
}
#' @rdname vec_is_list
#' @export
vec_check_list <- function(x,
...,
arg = caller_arg(x),
call = caller_env()) {
# Silently-deprecated: 2023-03
# lifecycle::deprecate_soft("0.6.0", "vec_check_list()", "obj_check_list()")
obj_check_list(x, ..., arg = arg, call = call)
}
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/vctrs-deprecated.R
|
#' @description
#' `r lifecycle::badge("maturing")`
#'
#' Defines new notions of prototype and size that are
#' used to provide tools for consistent and well-founded type-coercion
#' and size-recycling, and are in turn connected to ideas of type- and
#' size-stability useful for analysing function interfaces.
#'
#' @keywords internal
#' @import rlang
#' @useDynLib vctrs, .registration = TRUE
"_PACKAGE"
release_extra_revdeps <- function() {
# Extra revdeps to run before release.
# Recognized by `usethis::use_release_issue()`.
c("dplyr", "tidyr", "purrr")
}
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/vctrs-package.R
|
# nocov start
.onLoad <- function(libname, pkgname) {
check_linked_version(pkgname)
ns <- ns_env("vctrs")
run_on_load()
on_package_load("testthat", {
s3_register("testthat::is_informative_error", "vctrs_error_cast_lossy", is_informative_error_vctrs_error_cast_lossy)
s3_register("testthat::is_informative_error", "vctrs_error_cast_lossy_dropped", is_informative_error_vctrs_error_cast_lossy_dropped)
})
s3_register("generics::as.factor", "vctrs_vctr")
s3_register("generics::as.ordered", "vctrs_vctr")
s3_register("generics::as.difftime", "vctrs_vctr")
# Remove once tibble has implemented the methods
on_package_load("tibble", {
if (!env_has(ns_env("tibble"), "vec_ptype2.tbl_df.tbl_df")) {
s3_register("vctrs::vec_ptype2", "tbl_df.tbl_df", vec_ptype2_tbl_df_tbl_df)
s3_register("vctrs::vec_ptype2", "tbl_df.data.frame", vec_ptype2_tbl_df_data.frame)
s3_register("vctrs::vec_ptype2", "data.frame.tbl_df", vec_ptype2_data.frame_tbl_df)
}
if (!env_has(ns_env("tibble"), "vec_cast.tbl_df.tbl_df")) {
s3_register("vctrs::vec_cast", "tbl_df.tbl_df", vec_cast_tbl_df_tbl_df)
s3_register("vctrs::vec_cast", "tbl_df.data.frame", vec_cast_tbl_df_data.frame)
s3_register("vctrs::vec_cast", "data.frame.tbl_df", vec_cast_data.frame_tbl_df)
}
})
on_package_load("dplyr", {
if (!env_has(ns_env("dplyr"), "vec_restore.grouped_df")) {
s3_register("vctrs::vec_restore", "grouped_df", vec_restore_grouped_df)
}
if (!env_has(ns_env("dplyr"), "vec_ptype2.grouped_df.grouped_df")) {
s3_register("vctrs::vec_ptype2", "grouped_df.grouped_df", vec_ptype2_grouped_df_grouped_df)
s3_register("vctrs::vec_ptype2", "grouped_df.data.frame", vec_ptype2_grouped_df_data.frame)
s3_register("vctrs::vec_ptype2", "grouped_df.tbl_df", vec_ptype2_grouped_df_tbl_df)
s3_register("vctrs::vec_ptype2", "data.frame.grouped_df", vec_ptype2_data.frame_grouped_df)
s3_register("vctrs::vec_ptype2", "tbl_df.grouped_df", vec_ptype2_tbl_df_grouped_df)
}
if (!env_has(ns_env("dplyr"), "vec_cast.grouped_df.grouped_df")) {
s3_register("vctrs::vec_cast", "grouped_df.grouped_df", vec_cast_grouped_df_grouped_df)
s3_register("vctrs::vec_cast", "grouped_df.data.frame", vec_cast_grouped_df_data.frame)
s3_register("vctrs::vec_cast", "grouped_df.tbl_df", vec_cast_grouped_df_tbl_df)
s3_register("vctrs::vec_cast", "data.frame.grouped_df", vec_cast_data.frame_grouped_df)
s3_register("vctrs::vec_cast", "tbl_df.grouped_df", vec_cast_tbl_df_grouped_df)
}
if (!env_has(ns_env("dplyr"), "vec_restore.rowwise_df")) {
s3_register("vctrs::vec_restore", "rowwise_df", vec_restore_rowwise_df)
}
if (!env_has(ns_env("dplyr"), "vec_ptype2.rowwise_df.rowwise_df")) {
s3_register("vctrs::vec_ptype2", "rowwise_df.rowwise_df", vec_ptype2_rowwise_df_rowwise_df)
s3_register("vctrs::vec_ptype2", "rowwise_df.data.frame", vec_ptype2_rowwise_df_data.frame)
s3_register("vctrs::vec_ptype2", "rowwise_df.tbl_df", vec_ptype2_rowwise_df_tbl_df)
s3_register("vctrs::vec_ptype2", "data.frame.rowwise_df", vec_ptype2_data.frame_rowwise_df)
s3_register("vctrs::vec_ptype2", "tbl_df.rowwise_df", vec_ptype2_tbl_df_rowwise_df)
}
if (!env_has(ns_env("dplyr"), "vec_cast.rowwise_df.rowwise_df")) {
s3_register("vctrs::vec_cast", "rowwise_df.rowwise_df", vec_cast_rowwise_df_rowwise_df)
s3_register("vctrs::vec_cast", "rowwise_df.data.frame", vec_cast_rowwise_df_data.frame)
s3_register("vctrs::vec_cast", "rowwise_df.tbl_df", vec_cast_rowwise_df_tbl_df)
s3_register("vctrs::vec_cast", "data.frame.rowwise_df", vec_cast_data.frame_rowwise_df)
s3_register("vctrs::vec_cast", "tbl_df.rowwise_df", vec_cast_tbl_df_rowwise_df)
}
})
on_package_load("sf", {
import_from("sf", sf_deps, env = sf_env)
if (!env_has(ns_env("sf"), "vec_restore.sf")) {
s3_register("vctrs::vec_proxy", "sf", vec_proxy_sf)
s3_register("vctrs::vec_restore", "sf", vec_restore_sf)
}
if (!env_has(ns_env("sf"), "vec_ptype2.sf.sf")) {
s3_register("vctrs::vec_ptype2", "sf.sf", vec_ptype2_sf_sf)
s3_register("vctrs::vec_ptype2", "sf.data.frame", vec_ptype2_sf_data.frame)
s3_register("vctrs::vec_ptype2", "data.frame.sf", vec_ptype2_data.frame_sf)
s3_register("vctrs::vec_ptype2", "sf.tbl_df", vec_ptype2_sf_tbl_df)
s3_register("vctrs::vec_ptype2", "tbl_df.sf", vec_ptype2_tbl_df_sf)
s3_register("vctrs::vec_cast", "sf.sf", vec_cast_sf_sf)
s3_register("vctrs::vec_cast", "sf.data.frame", vec_cast_sf_data.frame)
s3_register("vctrs::vec_cast", "data.frame.sf", vec_cast_data.frame_sf)
}
if (!env_has(ns_env("sf"), "vec_proxy_order.sfc")) {
s3_register("vctrs::vec_proxy_order", "sfc", vec_proxy_order_sfc)
}
})
utils::globalVariables("vec_set_attributes")
# Prevent two copies from being made by `attributes(x) <- attrib` on R < 3.6.0
if (getRversion() >= '3.6.0') {
vec_set_attributes <- function(x, attrib) {
attributes(x) <- attrib
x
}
} else {
vec_set_attributes <- function(x, attrib) {
.Call(vctrs_set_attributes, x, attrib)
}
}
env_bind(ns, vec_set_attributes = vec_set_attributes)
.Call(vctrs_init_library, ns_env())
}
# nocov end
|
/scratch/gouwar.j/cran-all/cranData/vctrs/R/zzz.R
|
## ----include = FALSE----------------------------------------------------------
knitr::opts_chunk$set(collapse = TRUE, comment = "#>")
## ----setup--------------------------------------------------------------------
library(vctrs)
library(pillar)
## ----eval = FALSE-------------------------------------------------------------
# usethis::use_package("vctrs")
# usethis::use_package("pillar")
## -----------------------------------------------------------------------------
#' @export
latlon <- function(lat, lon) {
new_rcrd(list(lat = lat, lon = lon), class = "earth_latlon")
}
#' @export
format.earth_latlon <- function(x, ..., formatter = deg_min) {
x_valid <- which(!is.na(x))
lat <- field(x, "lat")[x_valid]
lon <- field(x, "lon")[x_valid]
ret <- rep(NA_character_, vec_size(x))
ret[x_valid] <- paste0(formatter(lat, "lat"), " ", formatter(lon, "lon"))
# It's important to keep NA in the vector!
ret
}
deg_min <- function(x, direction) {
pm <- if (direction == "lat") c("N", "S") else c("E", "W")
sign <- sign(x)
x <- abs(x)
deg <- trunc(x)
x <- x - deg
min <- round(x * 60)
# Ensure the columns are always the same width so they line up nicely
ret <- sprintf("%d°%.2d'%s", deg, min, ifelse(sign >= 0, pm[[1]], pm[[2]]))
format(ret, justify = "right")
}
latlon(c(32.71, 2.95), c(-117.17, 1.67))
## -----------------------------------------------------------------------------
library(tibble)
loc <- latlon(
c(28.3411783, 32.7102978, 30.2622356, 37.7859102, 28.5, NA),
c(-81.5480348, -117.1704058, -97.7403327, -122.4131357, -81.4, NA)
)
data <- tibble(venue = "rstudio::conf", year = 2017:2022, loc = loc)
data
## -----------------------------------------------------------------------------
#' @export
vec_ptype_abbr.earth_latlon <- function(x) {
"latlon"
}
data
## -----------------------------------------------------------------------------
deg_min_color <- function(x, direction) {
pm <- if (direction == "lat") c("N", "S") else c("E", "W")
sign <- sign(x)
x <- abs(x)
deg <- trunc(x)
x <- x - deg
rad <- round(x * 60)
ret <- sprintf(
"%d%s%.2d%s%s",
deg,
pillar::style_subtle("°"),
rad,
pillar::style_subtle("'"),
pm[ifelse(sign >= 0, 1, 2)]
)
format(ret, justify = "right")
}
## -----------------------------------------------------------------------------
#' @importFrom pillar pillar_shaft
#' @export
pillar_shaft.earth_latlon <- function(x, ...) {
out <- format(x, formatter = deg_min_color)
pillar::new_pillar_shaft_simple(out, align = "right")
}
## -----------------------------------------------------------------------------
data
## -----------------------------------------------------------------------------
print(data, width = 30)
## -----------------------------------------------------------------------------
#' @importFrom pillar pillar_shaft
#' @export
pillar_shaft.earth_latlon <- function(x, ...) {
out <- format(x)
pillar::new_pillar_shaft_simple(out, align = "right", min_width = 10)
}
print(data, width = 30)
## -----------------------------------------------------------------------------
deg <- function(x, direction) {
pm <- if (direction == "lat") c("N", "S") else c("E", "W")
sign <- sign(x)
x <- abs(x)
deg <- round(x)
ret <- sprintf("%d°%s", deg, pm[ifelse(sign >= 0, 1, 2)])
format(ret, justify = "right")
}
## -----------------------------------------------------------------------------
#' @importFrom pillar pillar_shaft
#' @export
pillar_shaft.earth_latlon <- function(x, ...) {
deg <- format(x, formatter = deg)
deg_min <- format(x)
pillar::new_pillar_shaft(
list(deg = deg, deg_min = deg_min),
width = pillar::get_max_extent(deg_min),
min_width = pillar::get_max_extent(deg),
class = "pillar_shaft_latlon"
)
}
## -----------------------------------------------------------------------------
#' @export
format.pillar_shaft_latlon <- function(x, width, ...) {
if (get_max_extent(x$deg_min) <= width) {
ornament <- x$deg_min
} else {
ornament <- x$deg
}
pillar::new_ornament(ornament, align = "right")
}
data
print(data, width = 30)
## ----eval = FALSE-------------------------------------------------------------
# expect_snapshot(pillar_shaft(data$loc))
|
/scratch/gouwar.j/cran-all/cranData/vctrs/inst/doc/pillar.R
|
---
title: "Printing vectors nicely in tibbles"
author: "Kirill Müller, Hadley Wickham"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Printing vectors nicely in tibbles}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r, include = FALSE}
knitr::opts_chunk$set(collapse = TRUE, comment = "#>")
```
You can get basic control over how a vector is printed in a tibble by providing a `format()` method.
If you want greater control, you need to understand how printing works.
The presentation of a column in a tibble is controlled by two S3 generics:
* `vctrs::vec_ptype_abbr()` determines what goes into the column header.
* `pillar::pillar_shaft()` determines what goes into the body, or the shaft, of the column.
Technically a [*pillar*](https://en.wikipedia.org/wiki/Column#Nomenclature) is composed of a *shaft* (decorated with an *ornament*), with a *capital* above and a *base* below.
Multiple pillars form a *colonnade*, which can be stacked in multiple *tiers*.
This is the motivation behind the names in our API.
This short vignette shows the basics of column styling using a `"latlon"` vector.
The vignette imagines the code is in a package, so that you can see the roxygen2 commands you'll need to create documentation and the `NAMESPACE` file.
In this vignette, we'll attach pillar and vctrs:
```{r setup}
library(vctrs)
library(pillar)
```
You don't need to do this in a package.
Instead, you'll need to _import_ the packages by then to the `Imports:` section of your `DESCRIPTION`.
The following helper does this for you:
```{r, eval = FALSE}
usethis::use_package("vctrs")
usethis::use_package("pillar")
```
## Prerequisites
To illustrate the basic ideas we're going to create a `"latlon"` class that encodes geographic coordinates in a record.
We'll pretend that this code lives in a package called earth.
For simplicity, the values are printed as degrees and minutes only.
By using `vctrs_rcrd()`, we already get the infrastructure to make this class fully compatible with data frames for free.
See `vignette("s3-vector", package = "vctrs")` for details on the record data type.
```{r}
#' @export
latlon <- function(lat, lon) {
new_rcrd(list(lat = lat, lon = lon), class = "earth_latlon")
}
#' @export
format.earth_latlon <- function(x, ..., formatter = deg_min) {
x_valid <- which(!is.na(x))
lat <- field(x, "lat")[x_valid]
lon <- field(x, "lon")[x_valid]
ret <- rep(NA_character_, vec_size(x))
ret[x_valid] <- paste0(formatter(lat, "lat"), " ", formatter(lon, "lon"))
# It's important to keep NA in the vector!
ret
}
deg_min <- function(x, direction) {
pm <- if (direction == "lat") c("N", "S") else c("E", "W")
sign <- sign(x)
x <- abs(x)
deg <- trunc(x)
x <- x - deg
min <- round(x * 60)
# Ensure the columns are always the same width so they line up nicely
ret <- sprintf("%d°%.2d'%s", deg, min, ifelse(sign >= 0, pm[[1]], pm[[2]]))
format(ret, justify = "right")
}
latlon(c(32.71, 2.95), c(-117.17, 1.67))
```
## Using in a tibble
Columns of this class can be used in a tibble right away because we've made a class using the vctrs infrastructure and have provided a `format()` method:
```{r}
library(tibble)
loc <- latlon(
c(28.3411783, 32.7102978, 30.2622356, 37.7859102, 28.5, NA),
c(-81.5480348, -117.1704058, -97.7403327, -122.4131357, -81.4, NA)
)
data <- tibble(venue = "rstudio::conf", year = 2017:2022, loc = loc)
data
```
This output is ok, but we could improve it by:
1. Using a more description type abbreviation than `<erth_ltl>`.
1. Using a dash of colour to highlight the most important parts of the value.
1. Providing a narrower view when horizontal space is at a premium.
The following sections show how to enhance the rendering.
## Fixing the data type
Instead of `<erth_ltl>` we'd prefer to use `<latlon>`.
We can do that by implementing the `vec_ptype_abbr()` method, which should return a string that can be used in a column header.
For your own classes, strive for an evocative abbreviation that's under 6 characters.
```{r}
#' @export
vec_ptype_abbr.earth_latlon <- function(x) {
"latlon"
}
data
```
## Custom rendering
The `format()` method is used by default for rendering.
For custom formatting you need to implement the `pillar_shaft()` method.
This function should always return a pillar shaft object, created by `new_pillar_shaft_simple()` or similar.
`new_pillar_shaft_simple()` accepts ANSI escape codes for colouring, and pillar includes some built in styles like `style_subtle()`.
We can use subtle style for the degree and minute separators to make the data more obvious.
First we define a degree formatter that makes use of `style_subtle()`:
```{r}
deg_min_color <- function(x, direction) {
pm <- if (direction == "lat") c("N", "S") else c("E", "W")
sign <- sign(x)
x <- abs(x)
deg <- trunc(x)
x <- x - deg
rad <- round(x * 60)
ret <- sprintf(
"%d%s%.2d%s%s",
deg,
pillar::style_subtle("°"),
rad,
pillar::style_subtle("'"),
pm[ifelse(sign >= 0, 1, 2)]
)
format(ret, justify = "right")
}
```
And then we pass that to our `format()` method:
```{r}
#' @importFrom pillar pillar_shaft
#' @export
pillar_shaft.earth_latlon <- function(x, ...) {
out <- format(x, formatter = deg_min_color)
pillar::new_pillar_shaft_simple(out, align = "right")
}
```
Currently, ANSI escapes are not rendered in vignettes, so this result doesn't look any different, but if you run the code yourself you'll see an improved display.
```{r}
data
```
As well as the functions in pillar, the [cli](https://cli.r-lib.org/) package provides a variety of tools for styling text.
## Truncation
Tibbles can automatically compacts columns when there's no enough horizontal space to display everything:
```{r}
print(data, width = 30)
```
Currently the latlon class isn't ever compacted because we haven't specified a minimum width when constructing the shaft.
Let's fix that and re-print the data:
```{r}
#' @importFrom pillar pillar_shaft
#' @export
pillar_shaft.earth_latlon <- function(x, ...) {
out <- format(x)
pillar::new_pillar_shaft_simple(out, align = "right", min_width = 10)
}
print(data, width = 30)
```
## Adaptive rendering
Truncation may be useful for character data, but for lat-lon data it'd be nicer to show full degrees and remove the minutes.
We'll first write a function that does this:
```{r}
deg <- function(x, direction) {
pm <- if (direction == "lat") c("N", "S") else c("E", "W")
sign <- sign(x)
x <- abs(x)
deg <- round(x)
ret <- sprintf("%d°%s", deg, pm[ifelse(sign >= 0, 1, 2)])
format(ret, justify = "right")
}
```
Then use it as part of more sophisticated implementation of the `pillar_shaft()` method:
```{r}
#' @importFrom pillar pillar_shaft
#' @export
pillar_shaft.earth_latlon <- function(x, ...) {
deg <- format(x, formatter = deg)
deg_min <- format(x)
pillar::new_pillar_shaft(
list(deg = deg, deg_min = deg_min),
width = pillar::get_max_extent(deg_min),
min_width = pillar::get_max_extent(deg),
class = "pillar_shaft_latlon"
)
}
```
Now the `pillar_shaft()` method returns an object of class `"pillar_shaft_latlon"` created by `new_pillar_shaft()`.
This object contains the necessary information to render the values, and also minimum and maximum width values.
For simplicity, both formats are pre-rendered, and the minimum and maximum widths are computed from there.
(`get_max_extent()` is a helper that computes the maximum display width occupied by the values in a character vector.)
All that's left to do is to implement a `format()` method for our new `"pillar_shaft_latlon"` class.
This method will be called with a `width` argument, which then determines which of the formats to choose.
The formatting of our choice is passed to the `new_ornament()` function:
```{r}
#' @export
format.pillar_shaft_latlon <- function(x, width, ...) {
if (get_max_extent(x$deg_min) <= width) {
ornament <- x$deg_min
} else {
ornament <- x$deg
}
pillar::new_ornament(ornament, align = "right")
}
data
print(data, width = 30)
```
## Testing
If you want to test the output of your code, you can compare it with a known state recorded in a text file. The `testthat::expect_snapshot()` function offers an easy way to test output-generating functions. It takes care about details such as Unicode, ANSI escapes, and output width. Furthermore it won't make the tests fail on CRAN. This is important because your output may rely on details out of your control, which should be fixed eventually but should not lead to your package being removed from CRAN.
Use this testthat expectation in one of your test files to create a snapshot test:
```{r eval = FALSE}
expect_snapshot(pillar_shaft(data$loc))
```
See <https://testthat.r-lib.org/articles/snapshotting.html> for more information.
|
/scratch/gouwar.j/cran-all/cranData/vctrs/inst/doc/pillar.Rmd
|
## ----include = FALSE----------------------------------------------------------
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
set.seed(1014)
## ----setup--------------------------------------------------------------------
library(vctrs)
library(rlang)
library(zeallot)
## -----------------------------------------------------------------------------
new_percent <- function(x = double()) {
if (!is_double(x)) {
abort("`x` must be a double vector.")
}
new_vctr(x, class = "vctrs_percent")
}
x <- new_percent(c(seq(0, 1, length.out = 4), NA))
x
str(x)
## -----------------------------------------------------------------------------
percent <- function(x = double()) {
x <- vec_cast(x, double())
new_percent(x)
}
## -----------------------------------------------------------------------------
new_percent()
percent()
## -----------------------------------------------------------------------------
is_percent <- function(x) {
inherits(x, "vctrs_percent")
}
## -----------------------------------------------------------------------------
format.vctrs_percent <- function(x, ...) {
out <- formatC(signif(vec_data(x) * 100, 3))
out[is.na(x)] <- NA
out[!is.na(x)] <- paste0(out[!is.na(x)], "%")
out
}
## ----include = FALSE----------------------------------------------------------
# As of R 3.5, print.vctr can not find format.percent since it's not in
# its lexical environment. We fix that problem by manually registering.
s3_register("base::format", "vctrs_percent")
## -----------------------------------------------------------------------------
x
## -----------------------------------------------------------------------------
data.frame(x)
## -----------------------------------------------------------------------------
vec_ptype_abbr.vctrs_percent <- function(x, ...) {
"prcnt"
}
tibble::tibble(x)
str(x)
## ----error = TRUE-------------------------------------------------------------
vec_ptype2("bogus", percent())
vec_ptype2(percent(), NA)
vec_ptype2(NA, percent())
## -----------------------------------------------------------------------------
vec_ptype2(percent(), percent())
## -----------------------------------------------------------------------------
vec_ptype2.vctrs_percent.vctrs_percent <- function(x, y, ...) new_percent()
## -----------------------------------------------------------------------------
vec_ptype2.vctrs_percent.double <- function(x, y, ...) double()
vec_ptype2.double.vctrs_percent <- function(x, y, ...) double()
## -----------------------------------------------------------------------------
vec_ptype_show(percent(), double(), percent())
## -----------------------------------------------------------------------------
vec_cast.vctrs_percent.vctrs_percent <- function(x, to, ...) x
## -----------------------------------------------------------------------------
vec_cast.vctrs_percent.double <- function(x, to, ...) percent(x)
vec_cast.double.vctrs_percent <- function(x, to, ...) vec_data(x)
## -----------------------------------------------------------------------------
vec_cast(0.5, percent())
vec_cast(percent(0.5), double())
## ----error = TRUE-------------------------------------------------------------
vec_c(percent(0.5), 1)
vec_c(NA, percent(0.5))
# but
vec_c(TRUE, percent(0.5))
x <- percent(c(0.5, 1, 2))
x[1:2] <- 2:1
x[[3]] <- 0.5
x
## ----error = TRUE-------------------------------------------------------------
# Correct
c(percent(0.5), 1)
c(percent(0.5), factor(1))
# Incorrect
c(factor(1), percent(0.5))
## -----------------------------------------------------------------------------
as_percent <- function(x) {
vec_cast(x, new_percent())
}
## -----------------------------------------------------------------------------
as_percent <- function(x, ...) {
UseMethod("as_percent")
}
as_percent.default <- function(x, ...) {
vec_cast(x, new_percent())
}
as_percent.character <- function(x) {
value <- as.numeric(gsub(" *% *$", "", x)) / 100
new_percent(value)
}
## -----------------------------------------------------------------------------
new_decimal <- function(x = double(), digits = 2L) {
if (!is_double(x)) {
abort("`x` must be a double vector.")
}
if (!is_integer(digits)) {
abort("`digits` must be an integer vector.")
}
vec_check_size(digits, size = 1L)
new_vctr(x, digits = digits, class = "vctrs_decimal")
}
decimal <- function(x = double(), digits = 2L) {
x <- vec_cast(x, double())
digits <- vec_recycle(vec_cast(digits, integer()), 1L)
new_decimal(x, digits = digits)
}
digits <- function(x) attr(x, "digits")
format.vctrs_decimal <- function(x, ...) {
sprintf(paste0("%-0.", digits(x), "f"), x)
}
vec_ptype_abbr.vctrs_decimal <- function(x, ...) {
"dec"
}
x <- decimal(runif(10), 1L)
x
## -----------------------------------------------------------------------------
x[1:2]
x[[1]]
## -----------------------------------------------------------------------------
vec_ptype_full.vctrs_decimal <- function(x, ...) {
paste0("decimal<", digits(x), ">")
}
x
## -----------------------------------------------------------------------------
vec_ptype2.vctrs_decimal.vctrs_decimal <- function(x, y, ...) {
new_decimal(digits = max(digits(x), digits(y)))
}
vec_cast.vctrs_decimal.vctrs_decimal <- function(x, to, ...) {
new_decimal(vec_data(x), digits = digits(to))
}
vec_c(decimal(1/100, digits = 3), decimal(2/100, digits = 2))
## -----------------------------------------------------------------------------
vec_ptype2.vctrs_decimal.double <- function(x, y, ...) x
vec_ptype2.double.vctrs_decimal <- function(x, y, ...) y
vec_cast.vctrs_decimal.double <- function(x, to, ...) new_decimal(x, digits = digits(to))
vec_cast.double.vctrs_decimal <- function(x, to, ...) vec_data(x)
vec_c(decimal(1, digits = 1), pi)
vec_c(pi, decimal(1, digits = 1))
## ----error = TRUE-------------------------------------------------------------
vec_cast(c(1, 2, 10), to = integer())
vec_cast(c(1.5, 2, 10.5), to = integer())
## -----------------------------------------------------------------------------
new_cached_sum <- function(x = double(), sum = 0L) {
if (!is_double(x)) {
abort("`x` must be a double vector.")
}
if (!is_double(sum)) {
abort("`sum` must be a double vector.")
}
vec_check_size(sum, size = 1L)
new_vctr(x, sum = sum, class = "vctrs_cached_sum")
}
cached_sum <- function(x) {
x <- vec_cast(x, double())
new_cached_sum(x, sum(x))
}
## -----------------------------------------------------------------------------
obj_print_footer.vctrs_cached_sum <- function(x, ...) {
cat("# Sum: ", format(attr(x, "sum"), digits = 3), "\n", sep = "")
}
x <- cached_sum(runif(10))
x
## -----------------------------------------------------------------------------
vec_math.vctrs_cached_sum <- function(.fn, .x, ...) {
cat("Using cache\n")
switch(.fn,
sum = attr(.x, "sum"),
mean = attr(.x, "sum") / length(.x),
vec_math_base(.fn, .x, ...)
)
}
sum(x)
## -----------------------------------------------------------------------------
x[1:2]
## -----------------------------------------------------------------------------
vec_restore.vctrs_cached_sum <- function(x, to, ..., i = NULL) {
new_cached_sum(x, sum(x))
}
x[1]
## -----------------------------------------------------------------------------
x <- as.POSIXlt(ISOdatetime(2020, 1, 1, 0, 0, 1:3))
x
length(x)
length(unclass(x))
x[[1]] # the first date time
unclass(x)[[1]] # the first component, the number of seconds
## -----------------------------------------------------------------------------
new_rational <- function(n = integer(), d = integer()) {
if (!is_integer(n)) {
abort("`n` must be an integer vector.")
}
if (!is_integer(d)) {
abort("`d` must be an integer vector.")
}
new_rcrd(list(n = n, d = d), class = "vctrs_rational")
}
## -----------------------------------------------------------------------------
rational <- function(n = integer(), d = integer()) {
c(n, d) %<-% vec_cast_common(n, d, .to = integer())
c(n, d) %<-% vec_recycle_common(n, d)
new_rational(n, d)
}
x <- rational(1, 1:10)
## -----------------------------------------------------------------------------
names(x)
length(x)
## -----------------------------------------------------------------------------
fields(x)
field(x, "n")
## ----error = TRUE-------------------------------------------------------------
x
str(x)
## -----------------------------------------------------------------------------
vec_data(x)
str(vec_data(x))
## -----------------------------------------------------------------------------
format.vctrs_rational <- function(x, ...) {
n <- field(x, "n")
d <- field(x, "d")
out <- paste0(n, "/", d)
out[is.na(n) | is.na(d)] <- NA
out
}
vec_ptype_abbr.vctrs_rational <- function(x, ...) "rtnl"
vec_ptype_full.vctrs_rational <- function(x, ...) "rational"
x
## -----------------------------------------------------------------------------
str(x)
## -----------------------------------------------------------------------------
vec_ptype2.vctrs_rational.vctrs_rational <- function(x, y, ...) new_rational()
vec_ptype2.vctrs_rational.integer <- function(x, y, ...) new_rational()
vec_ptype2.integer.vctrs_rational <- function(x, y, ...) new_rational()
vec_cast.vctrs_rational.vctrs_rational <- function(x, to, ...) x
vec_cast.double.vctrs_rational <- function(x, to, ...) field(x, "n") / field(x, "d")
vec_cast.vctrs_rational.integer <- function(x, to, ...) rational(x, 1)
vec_c(rational(1, 2), 1L, NA)
## -----------------------------------------------------------------------------
new_decimal2 <- function(l, r, scale = 2L) {
if (!is_integer(l)) {
abort("`l` must be an integer vector.")
}
if (!is_integer(r)) {
abort("`r` must be an integer vector.")
}
if (!is_integer(scale)) {
abort("`scale` must be an integer vector.")
}
vec_check_size(scale, size = 1L)
new_rcrd(list(l = l, r = r), scale = scale, class = "vctrs_decimal2")
}
decimal2 <- function(l, r, scale = 2L) {
l <- vec_cast(l, integer())
r <- vec_cast(r, integer())
c(l, r) %<-% vec_recycle_common(l, r)
scale <- vec_cast(scale, integer())
# should check that r < 10^scale
new_decimal2(l = l, r = r, scale = scale)
}
format.vctrs_decimal2 <- function(x, ...) {
val <- field(x, "l") + field(x, "r") / 10^attr(x, "scale")
sprintf(paste0("%.0", attr(x, "scale"), "f"), val)
}
decimal2(10, c(0, 5, 99))
## -----------------------------------------------------------------------------
x <- rational(c(1, 2, 1, 2), c(1, 1, 2, 2))
x
vec_proxy(x)
x == rational(1, 1)
## -----------------------------------------------------------------------------
# Thanks to Matthew Lundberg: https://stackoverflow.com/a/21504113/16632
gcd <- function(x, y) {
r <- x %% y
ifelse(r, gcd(y, r), y)
}
vec_proxy_equal.vctrs_rational <- function(x, ...) {
n <- field(x, "n")
d <- field(x, "d")
gcd <- gcd(n, d)
data.frame(n = n / gcd, d = d / gcd)
}
vec_proxy_equal(x)
x == rational(1, 1)
## -----------------------------------------------------------------------------
unique(x)
## -----------------------------------------------------------------------------
rational(1, 2) < rational(2, 3)
rational(2, 4) < rational(2, 3)
## -----------------------------------------------------------------------------
vec_proxy_compare.vctrs_rational <- function(x, ...) {
field(x, "n") / field(x, "d")
}
rational(2, 4) < rational(2, 3)
## -----------------------------------------------------------------------------
sort(x)
## -----------------------------------------------------------------------------
poly <- function(...) {
x <- vec_cast_common(..., .to = integer())
new_poly(x)
}
new_poly <- function(x) {
new_list_of(x, ptype = integer(), class = "vctrs_poly_list")
}
vec_ptype_full.vctrs_poly_list <- function(x, ...) "polynomial"
vec_ptype_abbr.vctrs_poly_list <- function(x, ...) "poly"
format.vctrs_poly_list <- function(x, ...) {
format_one <- function(x) {
if (length(x) == 0) {
return("")
}
if (length(x) == 1) {
format(x)
} else {
suffix <- c(paste0("\u22C5x^", seq(length(x) - 1, 1)), "")
out <- paste0(x, suffix)
out <- out[x != 0L]
paste0(out, collapse = " + ")
}
}
vapply(x, format_one, character(1))
}
obj_print_data.vctrs_poly_list <- function(x, ...) {
if (length(x) != 0) {
print(format(x), quote = FALSE)
}
}
p <- poly(1, c(1, 0, 0, 0, 2), c(1, 0, 1))
p
## -----------------------------------------------------------------------------
class(p)
p[2]
p[[2]]
## -----------------------------------------------------------------------------
obj_is_list(p)
## -----------------------------------------------------------------------------
poly <- function(...) {
x <- vec_cast_common(..., .to = integer())
x <- new_poly(x)
new_rcrd(list(data = x), class = "vctrs_poly")
}
format.vctrs_poly <- function(x, ...) {
format(field(x, "data"))
}
## -----------------------------------------------------------------------------
p <- poly(1, c(1, 0, 0, 0, 2), c(1, 0, 1))
p
## -----------------------------------------------------------------------------
obj_is_list(p)
## -----------------------------------------------------------------------------
p[[2]]
## -----------------------------------------------------------------------------
p == poly(c(1, 0, 1))
## ----error = TRUE-------------------------------------------------------------
p < p[2]
## -----------------------------------------------------------------------------
vec_proxy_compare.vctrs_poly <- function(x, ...) {
# Get the list inside the record vector
x_raw <- vec_data(field(x, "data"))
# First figure out the maximum length
n <- max(vapply(x_raw, length, integer(1)))
# Then expand all vectors to this length by filling in with zeros
full <- lapply(x_raw, function(x) c(rep(0L, n - length(x)), x))
# Then turn into a data frame
as.data.frame(do.call(rbind, full))
}
p < p[2]
## -----------------------------------------------------------------------------
sort(p)
sort(p[c(1:3, 1:2)])
## -----------------------------------------------------------------------------
vec_proxy_order.vctrs_poly <- function(x, ...) {
vec_proxy_compare(x, ...)
}
sort(p)
## -----------------------------------------------------------------------------
vec_arith.MYCLASS <- function(op, x, y, ...) {
UseMethod("vec_arith.MYCLASS", y)
}
vec_arith.MYCLASS.default <- function(op, x, y, ...) {
stop_incompatible_op(op, x, y)
}
## -----------------------------------------------------------------------------
vec_math.vctrs_cached_sum <- function(.fn, .x, ...) {
switch(.fn,
sum = attr(.x, "sum"),
mean = attr(.x, "sum") / length(.x),
vec_math_base(.fn, .x, ...)
)
}
## -----------------------------------------------------------------------------
new_meter <- function(x) {
stopifnot(is.double(x))
new_vctr(x, class = "vctrs_meter")
}
format.vctrs_meter <- function(x, ...) {
paste0(format(vec_data(x)), " m")
}
meter <- function(x) {
x <- vec_cast(x, double())
new_meter(x)
}
x <- meter(1:10)
x
## -----------------------------------------------------------------------------
sum(x)
mean(x)
## ----error = TRUE-------------------------------------------------------------
x + 1
meter(10) + meter(1)
meter(10) * 3
## -----------------------------------------------------------------------------
vec_arith.vctrs_meter <- function(op, x, y, ...) {
UseMethod("vec_arith.vctrs_meter", y)
}
vec_arith.vctrs_meter.default <- function(op, x, y, ...) {
stop_incompatible_op(op, x, y)
}
## ----error = TRUE-------------------------------------------------------------
vec_arith.vctrs_meter.vctrs_meter <- function(op, x, y, ...) {
switch(
op,
"+" = ,
"-" = new_meter(vec_arith_base(op, x, y)),
"/" = vec_arith_base(op, x, y),
stop_incompatible_op(op, x, y)
)
}
meter(10) + meter(1)
meter(10) - meter(1)
meter(10) / meter(1)
meter(10) * meter(1)
## ----error = TRUE-------------------------------------------------------------
vec_arith.vctrs_meter.numeric <- function(op, x, y, ...) {
switch(
op,
"/" = ,
"*" = new_meter(vec_arith_base(op, x, y)),
stop_incompatible_op(op, x, y)
)
}
vec_arith.numeric.vctrs_meter <- function(op, x, y, ...) {
switch(
op,
"*" = new_meter(vec_arith_base(op, x, y)),
stop_incompatible_op(op, x, y)
)
}
meter(2) * 10
meter(2) * as.integer(10)
10 * meter(2)
meter(20) / 10
10 / meter(20)
meter(20) + 10
## -----------------------------------------------------------------------------
vec_arith.vctrs_meter.MISSING <- function(op, x, y, ...) {
switch(op,
`-` = x * -1,
`+` = x,
stop_incompatible_op(op, x, y)
)
}
-meter(1)
+meter(1)
## ----eval = FALSE-------------------------------------------------------------
# #' Internal vctrs methods
# #'
# #' @import vctrs
# #' @keywords internal
# #' @name pizza-vctrs
# NULL
## -----------------------------------------------------------------------------
new_percent <- function(x = double()) {
if (!is_double(x)) {
abort("`x` must be a double vector.")
}
new_vctr(x, class = "pizza_percent")
}
## -----------------------------------------------------------------------------
# for compatibility with the S4 system
methods::setOldClass(c("pizza_percent", "vctrs_vctr"))
## -----------------------------------------------------------------------------
#' `percent` vector
#'
#' This creates a double vector that represents percentages so when it is
#' printed, it is multiplied by 100 and suffixed with `%`.
#'
#' @param x A numeric vector
#' @return An S3 vector of class `pizza_percent`.
#' @export
#' @examples
#' percent(c(0.25, 0.5, 0.75))
percent <- function(x = double()) {
x <- vec_cast(x, double())
new_percent(x)
}
## -----------------------------------------------------------------------------
#' @export
#' @rdname percent
is_percent <- function(x) {
inherits(x, "pizza_percent")
}
## -----------------------------------------------------------------------------
#' @param x
#' * For `percent()`: A numeric vector
#' * For `is_percent()`: An object to test.
## ----eval = FALSE-------------------------------------------------------------
# #' @export
# format.pizza_percent <- function(x, ...) {
# out <- formatC(signif(vec_data(x) * 100, 3))
# out[is.na(x)] <- NA
# out[!is.na(x)] <- paste0(out[!is.na(x)], "%")
# out
# }
#
# #' @export
# vec_ptype_abbr.pizza_percent <- function(x, ...) {
# "prcnt"
# }
## ----eval = FALSE-------------------------------------------------------------
# #' @export
# vec_ptype2.vctrs_percent.vctrs_percent <- function(x, y, ...) new_percent()
# #' @export
# vec_ptype2.double.vctrs_percent <- function(x, y, ...) double()
#
# #' @export
# vec_cast.pizza_percent.pizza_percent <- function(x, to, ...) x
# #' @export
# vec_cast.pizza_percent.double <- function(x, to, ...) percent(x)
# #' @export
# vec_cast.double.pizza_percent <- function(x, to, ...) vec_data(x)
## ----eval=FALSE---------------------------------------------------------------
# #' @export
# #' @method vec_arith my_type
# vec_arith.my_type <- function(op, x, y, ...) {
# UseMethod("vec_arith.my_type", y)
# }
## ----eval=FALSE---------------------------------------------------------------
# #' @export
# #' @method vec_arith.my_type my_type
# vec_arith.my_type.my_type <- function(op, x, y, ...) {
# # implementation here
# }
#
# #' @export
# #' @method vec_arith.my_type integer
# vec_arith.my_type.integer <- function(op, x, y, ...) {
# # implementation here
# }
#
# #' @export
# #' @method vec_arith.integer my_type
# vec_arith.integer.my_type <- function(op, x, y, ...) {
# # implementation here
# }
## ----eval = FALSE-------------------------------------------------------------
# expect_error(vec_c(1, "a"), class = "vctrs_error_incompatible_type")
|
/scratch/gouwar.j/cran-all/cranData/vctrs/inst/doc/s3-vector.R
|
---
title: "S3 vectors"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{S3 vectors}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
set.seed(1014)
```
This vignette shows you how to create your own S3 vector classes.
It focuses on the aspects of making a vector class that every class needs to worry about; you'll also need to provide methods that actually make the vector useful.
I assume that you're already familiar with the basic machinery of S3, and the vocabulary I use in Advanced R: constructor, helper, and validator.
If not, I recommend reading at least the first two sections of [the S3 chapter](https://adv-r.hadley.nz/s3.html) of *Advanced R*.
This article refers to "vectors of numbers" as *double vectors*.
Here, "double" stands for ["double precision floating point number"](https://en.wikipedia.org/wiki/Double-precision_floating-point_format), see also `double()`.
```{r setup}
library(vctrs)
library(rlang)
library(zeallot)
```
This vignette works through five big topics:
- The basics of creating a new vector class with vctrs.
- The coercion and casting system.
- The record and list-of types.
- Equality and comparison proxies.
- Arithmetic operators.
They're collectively demonstrated with a number of simple S3 classes:
- Percent: a double vector that prints as a percentage.
This illustrates the basic mechanics of class creation, coercion, and casting.
- Decimal: a double vector that always prints with a fixed number of decimal places.
This class has an attribute which needs a little extra care in casts and coercions.
- Cached sum: a double vector that caches the total sum in an attribute.
The attribute depends on the data, so needs extra care.
- Rational: a pair of integer vectors that defines a rational number like `2 / 3`.
This introduces you to the record style, and to the equality and comparison operators.
It also needs special handling for `+`, `-`, and friends.
- Polynomial: a list of integer vectors that define polynomials like `1 + x - x^3`.
Sorting such vectors correctly requires a custom equality method.
- Meter: a numeric vector with meter units.
This is the simplest possible class with interesting algebraic properties.
- Period and frequency: a pair of classes represent a period, or its inverse, frequency.
This allows us to explore more arithmetic operators.
## Basics
In this section you'll learn how to create a new vctrs class by calling `new_vctr()`.
This creates an object with class `vctrs_vctr` which has a number of methods.
These are designed to make your life as easy as possible.
For example:
- The `print()` and `str()` methods are defined in terms of `format()` so you get a pleasant, consistent display as soon as you've made your `format()` method.
- You can immediately put your new vector class in a data frame because `as.data.frame.vctrs_vctr()` does the right thing.
- Subsetting (`[`, `[[`, and `$`), `length<-`, and `rep()` methods automatically preserve attributes because they use `vec_restore()`.
A default `vec_restore()` works for all classes where the attributes are data-independent, and can easily be customised when the attributes do depend on the data.
- Default subset-assignment methods (`[<-`, `[[<-`, and `$<-`) follow the principle that the new values should be coerced to match the existing vector.
This gives predictable behaviour and clear error messages.
### Percent class
In this section, I'll show you how to make a `percent` class, i.e., a double vector that is printed as a percentage.
We start by defining a low-level [constructor](https://adv-r.hadley.nz/s3.html#s3-constrcutor) to check types and/or sizes and call `new_vctr()`.
`percent` is built on a double vector of any length and doesn't have any attributes.
```{r}
new_percent <- function(x = double()) {
if (!is_double(x)) {
abort("`x` must be a double vector.")
}
new_vctr(x, class = "vctrs_percent")
}
x <- new_percent(c(seq(0, 1, length.out = 4), NA))
x
str(x)
```
Note that we prefix the name of the class with the name of the package.
This prevents conflicting definitions between packages.
For packages that implement only one class (such as [blob](https://blob.tidyverse.org/)), it's fine to use the package name without prefix as the class name.
We then follow up with a user friendly [helper](https://adv-r.hadley.nz/s3.html#helpers).
Here we'll use `vec_cast()` to allow it to accept anything coercible to a double:
```{r}
percent <- function(x = double()) {
x <- vec_cast(x, double())
new_percent(x)
}
```
Before you go on, check that user-friendly constructor returns a zero-length vector when called with no arguments.
This makes it easy to use as a prototype.
```{r}
new_percent()
percent()
```
For the convenience of your users, consider implementing an `is_percent()` function:
```{r}
is_percent <- function(x) {
inherits(x, "vctrs_percent")
}
```
### `format()` method
The first method for every class should almost always be a `format()` method.
This should return a character vector the same length as `x`.
The easiest way to do this is to rely on one of R's low-level formatting functions like `formatC()`:
```{r}
format.vctrs_percent <- function(x, ...) {
out <- formatC(signif(vec_data(x) * 100, 3))
out[is.na(x)] <- NA
out[!is.na(x)] <- paste0(out[!is.na(x)], "%")
out
}
```
```{r, include = FALSE}
# As of R 3.5, print.vctr can not find format.percent since it's not in
# its lexical environment. We fix that problem by manually registering.
s3_register("base::format", "vctrs_percent")
```
```{r}
x
```
(Note the use of `vec_data()` so `format()` doesn't get stuck in an infinite loop, and that I take a little care to not convert `NA` to `"NA"`; this leads to better printing.)
The format method is also used by data frames, tibbles, and `str()`:
```{r}
data.frame(x)
```
For optimal display, I recommend also defining an abbreviated type name, which should be 4-5 letters for commonly used vectors.
This is used in tibbles and in `str()`:
```{r}
vec_ptype_abbr.vctrs_percent <- function(x, ...) {
"prcnt"
}
tibble::tibble(x)
str(x)
```
If you need more control over printing in tibbles, implement a method for `pillar::pillar_shaft()`.
See `vignette("pillar", package = "vctrs")` for details.
## Casting and coercion
The next set of methods you are likely to need are those related to coercion and casting.
Coercion and casting are two sides of the same coin: changing the prototype of an existing object.
When the change happens *implicitly* (e.g in `c()`) we call it **coercion**; when the change happens *explicitly* (e.g. with `as.integer(x)`), we call it **casting**.
One of the main goals of vctrs is to put coercion and casting on a robust theoretical footing so it's possible to make accurate predictions about what (e.g.) `c(x, y)` should do when `x` and `y` have different prototypes.
vctrs achieves this goal through two generics:
- `vec_ptype2(x, y)` defines possible set of coercions.
It returns a prototype if `x` and `y` can be safely coerced to the same prototype; otherwise it returns an error.
The set of automatic coercions is usually quite small because too many tend to make code harder to reason about and silently propagate mistakes.
- `vec_cast(x, to)` defines the possible sets of casts.
It returns `x` translated to have prototype `to`, or throws an error if the conversion isn't possible.
The set of possible casts is a superset of possible coercions because they're requested explicitly.
### Double dispatch
Both generics use [**double dispatch**](https://en.wikipedia.org/wiki/Double_dispatch) which means that the implementation is selected based on the class of two arguments, not just one.
S3 does not natively support double dispatch, so we implement our own dispatch mechanism.
In practice, this means:
- You end up with method names with two classes, like `vec_ptype2.foo.bar()`.
- You don't need to implement default methods (they would never be called if you do).
- You can't call `NextMethod()`.
### Percent class {#percent}
We'll make our percent class coercible back and forth with double vectors.
`vec_ptype2()` provides a user friendly error message if the coercion doesn't exist and makes sure `NA` is handled in a standard way.
`NA` is technically a logical vector, but we want to stand in for a missing value of any type.
```{r, error = TRUE}
vec_ptype2("bogus", percent())
vec_ptype2(percent(), NA)
vec_ptype2(NA, percent())
```
By default and in simple cases, an object of the same class is compatible with itself:
```{r}
vec_ptype2(percent(), percent())
```
However this only works if the attributes for both objects are the same.
Also the default methods are a bit slower.
It is always a good idea to provide an explicit coercion method for the case of identical classes.
So we'll start by saying that a `vctrs_percent` combined with a `vctrs_percent` yields a `vctrs_percent`, which we indicate by returning a prototype generated by the constructor.
```{r}
vec_ptype2.vctrs_percent.vctrs_percent <- function(x, y, ...) new_percent()
```
Next we define methods that say that combining a `percent` and double should yield a `double`.
We avoid returning a `percent` here because errors in the scale (1 vs. 0.01) are more obvious with raw numbers.
Because double dispatch is a bit of a hack, we need to provide two methods.
It's your responsibility to ensure that each member of the pair returns the same result: if they don't you will get weird and unpredictable behaviour.
The double dispatch mechanism requires us to refer to the underlying type, `double`, in the method name.
If we implemented `vec_ptype2.vctrs_percent.numeric()`, it would never be called.
```{r}
vec_ptype2.vctrs_percent.double <- function(x, y, ...) double()
vec_ptype2.double.vctrs_percent <- function(x, y, ...) double()
```
We can check that we've implemented this correctly with `vec_ptype_show()`:
```{r}
vec_ptype_show(percent(), double(), percent())
```
The `vec_ptype2()` methods define which input is the richer type that vctrs should coerce to.
However, they don't perform any conversion.
This is the job of `vec_cast()`, which we implement next.
We'll provide a method to cast a percent to a percent:
```{r}
vec_cast.vctrs_percent.vctrs_percent <- function(x, to, ...) x
```
And then for converting back and forth between doubles.
To convert a double to a percent we use the `percent()` helper (not the constructor; this is unvalidated user input).
To convert a `percent` to a double, we strip the attributes.
Note that for historical reasons the order of argument in the signature is the opposite as for `vec_ptype2()`.
The class for `to` comes first, and the class for `x` comes second.
Again, the double dispatch mechanism requires us to refer to the underlying type, `double`, in the method name.
Implementing `vec_cast.vctrs_percent.numeric()` has no effect.
```{r}
vec_cast.vctrs_percent.double <- function(x, to, ...) percent(x)
vec_cast.double.vctrs_percent <- function(x, to, ...) vec_data(x)
```
Then we can check this works with `vec_cast()`:
```{r}
vec_cast(0.5, percent())
vec_cast(percent(0.5), double())
```
Once you've implemented `vec_ptype2()` and `vec_cast()`, you get `vec_c()`, `[<-`, and `[[<-` implementations for free.
```{r, error = TRUE}
vec_c(percent(0.5), 1)
vec_c(NA, percent(0.5))
# but
vec_c(TRUE, percent(0.5))
x <- percent(c(0.5, 1, 2))
x[1:2] <- 2:1
x[[3]] <- 0.5
x
```
You'll also get mostly correct behaviour for `c()`.
The exception is when you use `c()` with a base R class:
```{r, error = TRUE}
# Correct
c(percent(0.5), 1)
c(percent(0.5), factor(1))
# Incorrect
c(factor(1), percent(0.5))
```
Unfortunately there's no way to fix this problem with the current design of `c()`.
Again, as a convenience, consider providing an `as_percent()` function that makes use of the casts defined in your `vec_cast.vctrs_percent()` methods:
```{r}
as_percent <- function(x) {
vec_cast(x, new_percent())
}
```
Occasionally, it is useful to provide conversions that go beyond what's allowed in casting.
For example, we could offer a parsing method for character vectors.
In this case, `as_percent()` should be generic, the default method should cast, and then additional methods should implement more flexible conversion:
```{r}
as_percent <- function(x, ...) {
UseMethod("as_percent")
}
as_percent.default <- function(x, ...) {
vec_cast(x, new_percent())
}
as_percent.character <- function(x) {
value <- as.numeric(gsub(" *% *$", "", x)) / 100
new_percent(value)
}
```
### Decimal class
Now that you've seen the basics with a very simple S3 class, we'll gradually explore more complicated scenarios.
This section creates a `decimal` class that prints with the specified number of decimal places.
This is very similar to `percent` but now the class needs an attribute: the number of decimal places to display (an integer vector of length 1).
We start off as before, defining a low-level constructor, a user-friendly constructor, a `format()` method, and a `vec_ptype_abbr()`.
Note that additional object attributes are simply passed along to `new_vctr()`:
```{r}
new_decimal <- function(x = double(), digits = 2L) {
if (!is_double(x)) {
abort("`x` must be a double vector.")
}
if (!is_integer(digits)) {
abort("`digits` must be an integer vector.")
}
vec_check_size(digits, size = 1L)
new_vctr(x, digits = digits, class = "vctrs_decimal")
}
decimal <- function(x = double(), digits = 2L) {
x <- vec_cast(x, double())
digits <- vec_recycle(vec_cast(digits, integer()), 1L)
new_decimal(x, digits = digits)
}
digits <- function(x) attr(x, "digits")
format.vctrs_decimal <- function(x, ...) {
sprintf(paste0("%-0.", digits(x), "f"), x)
}
vec_ptype_abbr.vctrs_decimal <- function(x, ...) {
"dec"
}
x <- decimal(runif(10), 1L)
x
```
Note that I provide a little helper to extract the `digits` attribute.
This makes the code a little easier to read and should not be exported.
By default, vctrs assumes that attributes are independent of the data and so are automatically preserved.
You'll see what to do if the attributes are data dependent in the next section.
```{r}
x[1:2]
x[[1]]
```
For the sake of exposition, we'll assume that `digits` is an important attribute of the class and should be included in the full type:
```{r}
vec_ptype_full.vctrs_decimal <- function(x, ...) {
paste0("decimal<", digits(x), ">")
}
x
```
Now consider `vec_cast()` and `vec_ptype2()`.
Casting and coercing from one decimal to another requires a little thought as the values of the `digits` attribute might be different, and we need some way to reconcile them.
Here I've decided to chose the maximum of the two; other reasonable options are to take the value from the left-hand side or throw an error.
```{r}
vec_ptype2.vctrs_decimal.vctrs_decimal <- function(x, y, ...) {
new_decimal(digits = max(digits(x), digits(y)))
}
vec_cast.vctrs_decimal.vctrs_decimal <- function(x, to, ...) {
new_decimal(vec_data(x), digits = digits(to))
}
vec_c(decimal(1/100, digits = 3), decimal(2/100, digits = 2))
```
Finally, I can implement coercion to and from other types, like doubles.
When automatically coercing, I choose the richer type (i.e., the decimal).
```{r}
vec_ptype2.vctrs_decimal.double <- function(x, y, ...) x
vec_ptype2.double.vctrs_decimal <- function(x, y, ...) y
vec_cast.vctrs_decimal.double <- function(x, to, ...) new_decimal(x, digits = digits(to))
vec_cast.double.vctrs_decimal <- function(x, to, ...) vec_data(x)
vec_c(decimal(1, digits = 1), pi)
vec_c(pi, decimal(1, digits = 1))
```
If type `x` has greater resolution than `y`, there will be some inputs that lose precision.
These should generate errors using `stop_lossy_cast()`.
You can see that in action when casting from doubles to integers; only some doubles can become integers without losing resolution.
```{r, error = TRUE}
vec_cast(c(1, 2, 10), to = integer())
vec_cast(c(1.5, 2, 10.5), to = integer())
```
### Cached sum class {#cached-sum}
The next level up in complexity is an object that has data-dependent attributes.
To explore this idea we'll create a vector that caches the sum of its values.
As usual, we start with low-level and user-friendly constructors:
```{r}
new_cached_sum <- function(x = double(), sum = 0L) {
if (!is_double(x)) {
abort("`x` must be a double vector.")
}
if (!is_double(sum)) {
abort("`sum` must be a double vector.")
}
vec_check_size(sum, size = 1L)
new_vctr(x, sum = sum, class = "vctrs_cached_sum")
}
cached_sum <- function(x) {
x <- vec_cast(x, double())
new_cached_sum(x, sum(x))
}
```
For this class, we can use the default `format()` method, and instead, we'll customise the `obj_print_footer()` method.
This is a good place to display user facing attributes.
```{r}
obj_print_footer.vctrs_cached_sum <- function(x, ...) {
cat("# Sum: ", format(attr(x, "sum"), digits = 3), "\n", sep = "")
}
x <- cached_sum(runif(10))
x
```
We'll also override `sum()` and `mean()` to use the attribute.
This is easiest to do with `vec_math()`, which you'll learn about later.
```{r}
vec_math.vctrs_cached_sum <- function(.fn, .x, ...) {
cat("Using cache\n")
switch(.fn,
sum = attr(.x, "sum"),
mean = attr(.x, "sum") / length(.x),
vec_math_base(.fn, .x, ...)
)
}
sum(x)
```
As mentioned above, vctrs assumes that attributes are independent of the data.
This means that when we take advantage of the default methods, they'll work, but return the incorrect result:
```{r}
x[1:2]
```
To fix this, you need to provide a `vec_restore()` method.
Note that this method dispatches on the `to` argument.
```{r}
vec_restore.vctrs_cached_sum <- function(x, to, ..., i = NULL) {
new_cached_sum(x, sum(x))
}
x[1]
```
This works because most of the vctrs methods dispatch to the underlying base function by first stripping off extra attributes with `vec_data()` and then reapplying them again with `vec_restore()`.
The default `vec_restore()` method copies over all attributes, which is not appropriate when the attributes depend on the data.
Note that `vec_restore.class` is subtly different from `vec_cast.class.class()`.
`vec_restore()` is used when restoring attributes that have been lost; `vec_cast()` is used for coercions.
This is easier to understand with a concrete example.
Imagine factors were implemented with `new_vctr()`.
`vec_restore.factor()` would restore attributes back to an integer vector, but you would not want to allow manually casting an integer to a factor with `vec_cast()`.
## Record-style objects
Record-style objects use a list of equal-length vectors to represent individual components of the object.
The best example of this is `POSIXlt`, which underneath the hood is a list of 11 fields like year, month, and day.
Record-style classes override `length()` and subsetting methods to conceal this implementation detail.
```{r}
x <- as.POSIXlt(ISOdatetime(2020, 1, 1, 0, 0, 1:3))
x
length(x)
length(unclass(x))
x[[1]] # the first date time
unclass(x)[[1]] # the first component, the number of seconds
```
vctrs makes it easy to create new record-style classes using `new_rcrd()`, which has a wide selection of default methods.
### Rational class
A fraction, or rational number, can be represented by a pair of integer vectors representing the numerator (the number on top) and the denominator (the number on bottom), where the length of each vector must be the same.
To represent such a data structure we turn to a new base data type: the record (or rcrd for short).
As usual we start with low-level and user-friendly constructors.
The low-level constructor calls `new_rcrd()`, which needs a named list of equal-length vectors.
```{r}
new_rational <- function(n = integer(), d = integer()) {
if (!is_integer(n)) {
abort("`n` must be an integer vector.")
}
if (!is_integer(d)) {
abort("`d` must be an integer vector.")
}
new_rcrd(list(n = n, d = d), class = "vctrs_rational")
}
```
Our user friendly constructor casts `n` and `d` to integers and recycles them to the same length.
```{r}
rational <- function(n = integer(), d = integer()) {
c(n, d) %<-% vec_cast_common(n, d, .to = integer())
c(n, d) %<-% vec_recycle_common(n, d)
new_rational(n, d)
}
x <- rational(1, 1:10)
```
Behind the scenes, `x` is a named list with two elements.
But those details are hidden so that it behaves like a vector:
```{r}
names(x)
length(x)
```
To access the underlying fields we need to use `field()` and `fields()`:
```{r}
fields(x)
field(x, "n")
```
Notice that we can't `print()` or `str()` the new rational vector `x` yet.
Printing causes an error:
```{r, error = TRUE}
x
str(x)
```
This is because we haven't defined how our class can be printed from the underlying data.
Note that if you want to look under the hood during development, you can always call `vec_data(x)`.
```{r}
vec_data(x)
str(vec_data(x))
```
It is generally best to define a formatting method early in the development of a class.
The format method defines how to display the class so that it can be printed in the normal way:
```{r}
format.vctrs_rational <- function(x, ...) {
n <- field(x, "n")
d <- field(x, "d")
out <- paste0(n, "/", d)
out[is.na(n) | is.na(d)] <- NA
out
}
vec_ptype_abbr.vctrs_rational <- function(x, ...) "rtnl"
vec_ptype_full.vctrs_rational <- function(x, ...) "rational"
x
```
vctrs uses the `format()` method in `str()`, hiding the underlying implementation details from the user:
```{r}
str(x)
```
For `rational`, `vec_ptype2()` and `vec_cast()` follow the same pattern as `percent()`.
We allow coercion from integer and to doubles.
```{r}
vec_ptype2.vctrs_rational.vctrs_rational <- function(x, y, ...) new_rational()
vec_ptype2.vctrs_rational.integer <- function(x, y, ...) new_rational()
vec_ptype2.integer.vctrs_rational <- function(x, y, ...) new_rational()
vec_cast.vctrs_rational.vctrs_rational <- function(x, to, ...) x
vec_cast.double.vctrs_rational <- function(x, to, ...) field(x, "n") / field(x, "d")
vec_cast.vctrs_rational.integer <- function(x, to, ...) rational(x, 1)
vec_c(rational(1, 2), 1L, NA)
```
### Decimal2 class
The previous implementation of `decimal` was built on top of doubles.
This is a bad idea because decimal vectors are typically used when you care about precise values (i.e., dollars and cents in a bank account), and double values suffer from floating point problems.
A better implementation of a decimal class would be to use pair of integers, one for the value to the left of the decimal point, and the other for the value to the right (divided by a `scale`).
The following code is a very quick sketch of how you might start creating such a class:
```{r}
new_decimal2 <- function(l, r, scale = 2L) {
if (!is_integer(l)) {
abort("`l` must be an integer vector.")
}
if (!is_integer(r)) {
abort("`r` must be an integer vector.")
}
if (!is_integer(scale)) {
abort("`scale` must be an integer vector.")
}
vec_check_size(scale, size = 1L)
new_rcrd(list(l = l, r = r), scale = scale, class = "vctrs_decimal2")
}
decimal2 <- function(l, r, scale = 2L) {
l <- vec_cast(l, integer())
r <- vec_cast(r, integer())
c(l, r) %<-% vec_recycle_common(l, r)
scale <- vec_cast(scale, integer())
# should check that r < 10^scale
new_decimal2(l = l, r = r, scale = scale)
}
format.vctrs_decimal2 <- function(x, ...) {
val <- field(x, "l") + field(x, "r") / 10^attr(x, "scale")
sprintf(paste0("%.0", attr(x, "scale"), "f"), val)
}
decimal2(10, c(0, 5, 99))
```
## Equality and comparison
vctrs provides four "proxy" generics.
Two of these let you control how your class determines equality and comparison:
- `vec_proxy_equal()` returns a data vector suitable for comparison.
It underpins `==`, `!=`, `unique()`, `anyDuplicated()`, and `is.na()`.
- `vec_proxy_compare()` specifies how to compare the elements of your vector.
This proxy is used in `<`, `<=`, `>=`, `>`, `min()`, `max()`, `median()`, and `quantile()`.
Two other proxy generic are used for sorting for unordered data types and for accessing the raw data for exotic storage formats:
- `vec_proxy_order()` specifies how to sort the elements of your vector.
It is used in `xtfrm()`, which in turn is called by the `order()` and `sort()` functions.
This proxy was added to implement the behaviour of lists, which are sortable (their order proxy sorts by first occurrence) but not comparable (comparison operators cause an error).
Its default implementation for other classes calls `vec_proxy_compare()` and you normally don't need to implement this proxy.
- `vec_proxy()` returns the actual data of a vector.
This is useful when you store the data in a field of your class.
Most of the time, you shouldn't need to implement `vec_proxy()`.
The default behavior is as follows:
- `vec_proxy_equal()` calls `vec_proxy()`
- `vec_proxy_compare()` calls `vec_proxy_equal()`
- `vec_proxy_order()` calls `vec_proxy_compare()`
You should only implement these proxies when some preprocessing on the data is needed to make elements comparable.
In that case, defining these methods will get you a lot of behaviour for relatively little work.
These proxy functions should always return a simple object (either a bare vector or a data frame) that possesses the same properties as your class.
This permits efficient implementation of the vctrs internals because it allows dispatch to happen once in R, and then efficient computations can be written in C.
### Rational class
Let's explore these ideas by with the rational class we started on above.
By default, `vec_proxy()` converts a record to a data frame, and the default comparison works column by column:
```{r}
x <- rational(c(1, 2, 1, 2), c(1, 1, 2, 2))
x
vec_proxy(x)
x == rational(1, 1)
```
This makes sense as a default but isn't correct here because `rational(1, 1)` represents the same number as `rational(2, 2)`, so they should be equal.
We can fix that by implementing a `vec_proxy_equal()` method that divides `n` and `d` by their greatest common divisor:
```{r}
# Thanks to Matthew Lundberg: https://stackoverflow.com/a/21504113/16632
gcd <- function(x, y) {
r <- x %% y
ifelse(r, gcd(y, r), y)
}
vec_proxy_equal.vctrs_rational <- function(x, ...) {
n <- field(x, "n")
d <- field(x, "d")
gcd <- gcd(n, d)
data.frame(n = n / gcd, d = d / gcd)
}
vec_proxy_equal(x)
x == rational(1, 1)
```
`vec_proxy_equal()` is also used by `unique()`:
```{r}
unique(x)
```
We now need to fix the comparison operations similarly, since comparison currently happens lexicographically by `n`, then by `d`:
```{r}
rational(1, 2) < rational(2, 3)
rational(2, 4) < rational(2, 3)
```
The easiest fix is to convert the fraction to a floating point number and use this as a proxy:
```{r}
vec_proxy_compare.vctrs_rational <- function(x, ...) {
field(x, "n") / field(x, "d")
}
rational(2, 4) < rational(2, 3)
```
This also fixes `sort()`, because the default implementation of `vec_proxy_order()` calls `vec_proxy_compare()`.
```{r}
sort(x)
```
(We could have used the same approach in `vec_proxy_equal()`, but when working with floating point numbers it's not necessarily true that `x == y` implies that `d * x == d * y`.)
### Polynomial class
A related problem occurs if we build our vector on top of a list.
The following code defines a polynomial class that represents polynomials (like `1 + 3x - 2x^2`) using a list of integer vectors (like `c(1, 3, -2)`).
Note the use of `new_list_of()` in the constructor.
```{r}
poly <- function(...) {
x <- vec_cast_common(..., .to = integer())
new_poly(x)
}
new_poly <- function(x) {
new_list_of(x, ptype = integer(), class = "vctrs_poly_list")
}
vec_ptype_full.vctrs_poly_list <- function(x, ...) "polynomial"
vec_ptype_abbr.vctrs_poly_list <- function(x, ...) "poly"
format.vctrs_poly_list <- function(x, ...) {
format_one <- function(x) {
if (length(x) == 0) {
return("")
}
if (length(x) == 1) {
format(x)
} else {
suffix <- c(paste0("\u22C5x^", seq(length(x) - 1, 1)), "")
out <- paste0(x, suffix)
out <- out[x != 0L]
paste0(out, collapse = " + ")
}
}
vapply(x, format_one, character(1))
}
obj_print_data.vctrs_poly_list <- function(x, ...) {
if (length(x) != 0) {
print(format(x), quote = FALSE)
}
}
p <- poly(1, c(1, 0, 0, 0, 2), c(1, 0, 1))
p
```
The resulting objects will inherit from the `vctrs_list_of` class, which provides tailored methods for `$`, `[[`, the corresponding assignment operators, and other methods.
```{r}
class(p)
p[2]
p[[2]]
```
The class implements the list interface:
```{r}
obj_is_list(p)
```
This is fine for the internal implementation of this class but it would be more appropriate if it behaved like an atomic vector rather than a list.
#### Make an atomic polynomial vector
An atomic vector is a vector like integer or character for which `[[` returns the same type.
Unlike lists, you can't reach inside an atomic vector.
To make the polynomial class an atomic vector, we'll wrap the internal `list_of()` class within a record vector.
Usually records are used because they can store several fields of data for each observation.
Here we have only one, but we use the class anyway to inherit its atomicity.
```{r}
poly <- function(...) {
x <- vec_cast_common(..., .to = integer())
x <- new_poly(x)
new_rcrd(list(data = x), class = "vctrs_poly")
}
format.vctrs_poly <- function(x, ...) {
format(field(x, "data"))
}
```
The new `format()` method delegates to the one we wrote for the internal list.
The vector looks just like before:
```{r}
p <- poly(1, c(1, 0, 0, 0, 2), c(1, 0, 1))
p
```
Making the class atomic means that `obj_is_list()` now returns `FALSE`.
This prevents recursive algorithms that traverse lists from reaching too far inside the polynomial internals.
```{r}
obj_is_list(p)
```
Most importantly, it prevents users from reaching into the internals with `[[`:
```{r}
p[[2]]
```
#### Implementing equality and comparison
Equality works out of the box because we can tell if two integer vectors are equal:
```{r}
p == poly(c(1, 0, 1))
```
We can't compare individual elements, because the data is stored in a list and by default lists are not comparable:
```{r, error = TRUE}
p < p[2]
```
To enable comparison, we implement a `vec_proxy_compare()` method:
```{r}
vec_proxy_compare.vctrs_poly <- function(x, ...) {
# Get the list inside the record vector
x_raw <- vec_data(field(x, "data"))
# First figure out the maximum length
n <- max(vapply(x_raw, length, integer(1)))
# Then expand all vectors to this length by filling in with zeros
full <- lapply(x_raw, function(x) c(rep(0L, n - length(x)), x))
# Then turn into a data frame
as.data.frame(do.call(rbind, full))
}
p < p[2]
```
Often, this is sufficient to also implement `sort()`.
However, for lists, there is already a default `vec_proxy_order()` method that sorts by first occurrence:
```{r}
sort(p)
sort(p[c(1:3, 1:2)])
```
To ensure consistency between ordering and comparison, we forward `vec_proxy_order()` to `vec_proxy_compare()`:
```{r}
vec_proxy_order.vctrs_poly <- function(x, ...) {
vec_proxy_compare(x, ...)
}
sort(p)
```
## Arithmetic
vctrs also provides two mathematical generics that allow you to define a broad swath of mathematical behaviour at once:
- `vec_math(fn, x, ...)` specifies the behaviour of mathematical functions like `abs()`, `sum()`, and `mean()`.
(Note that `var()` and `sd()` can't be overridden, see `?vec_math()` for the complete list supported by `vec_math()`.)
- `vec_arith(op, x, y)` specifies the behaviour of the arithmetic operations like `+`, `-`, and `%%`.
(See `?vec_arith()` for the complete list.)
Both generics define the behaviour for multiple functions because `sum.vctrs_vctr(x)` calls `vec_math.vctrs_vctr("sum", x)`, and `x + y` calls `vec_math.x_class.y_class("+", x, y)`.
They're accompanied by `vec_math_base()` and `vec_arith_base()` which make it easy to call the underlying base R functions.
`vec_arith()` uses double dispatch and needs the following standard boilerplate:
```{r}
vec_arith.MYCLASS <- function(op, x, y, ...) {
UseMethod("vec_arith.MYCLASS", y)
}
vec_arith.MYCLASS.default <- function(op, x, y, ...) {
stop_incompatible_op(op, x, y)
}
```
Correctly exporting `vec_arith()` methods from a package is currently a little awkward.
See the instructions in the Arithmetic section of the "Implementing a vctrs S3 class in a package" section below.
### Cached sum class
I showed an example of `vec_math()` to define `sum()` and `mean()` methods for `cached_sum`.
Now let's talk about exactly how it works.
Most `vec_math()` functions will have a similar form.
You use a switch statement to handle the methods that you care about and fall back to `vec_math_base()` for those that you don't care about.
```{r}
vec_math.vctrs_cached_sum <- function(.fn, .x, ...) {
switch(.fn,
sum = attr(.x, "sum"),
mean = attr(.x, "sum") / length(.x),
vec_math_base(.fn, .x, ...)
)
}
```
### Meter class
To explore the infix arithmetic operators exposed by `vec_arith()` I'll create a new class that represents a measurement in `meter`s:
```{r}
new_meter <- function(x) {
stopifnot(is.double(x))
new_vctr(x, class = "vctrs_meter")
}
format.vctrs_meter <- function(x, ...) {
paste0(format(vec_data(x)), " m")
}
meter <- function(x) {
x <- vec_cast(x, double())
new_meter(x)
}
x <- meter(1:10)
x
```
Because `meter` is built on top of a double vector, basic mathematic operations work:
```{r}
sum(x)
mean(x)
```
But we can't do arithmetic:
```{r, error = TRUE}
x + 1
meter(10) + meter(1)
meter(10) * 3
```
To allow these infix functions to work, we'll need to provide `vec_arith()` generic.
But before we do that, let's think about what combinations of inputs we should support:
- It makes sense to add and subtract meters: that yields another meter.
We can divide a meter by another meter (yielding a unitless number), but we can't multiply meters (because that would yield an area).
- For a combination of meter and number multiplication and division by a number are acceptable.
Addition and subtraction don't make much sense as we, strictly speaking, are dealing with objects of different nature.
`vec_arith()` is another function that uses double dispatch, so as usual we start with a template.
```{r}
vec_arith.vctrs_meter <- function(op, x, y, ...) {
UseMethod("vec_arith.vctrs_meter", y)
}
vec_arith.vctrs_meter.default <- function(op, x, y, ...) {
stop_incompatible_op(op, x, y)
}
```
Then write the method for two meter objects.
We use a switch statement to cover the cases we care about and `stop_incompatible_op()` to throw an informative error message for everything else.
```{r, error = TRUE}
vec_arith.vctrs_meter.vctrs_meter <- function(op, x, y, ...) {
switch(
op,
"+" = ,
"-" = new_meter(vec_arith_base(op, x, y)),
"/" = vec_arith_base(op, x, y),
stop_incompatible_op(op, x, y)
)
}
meter(10) + meter(1)
meter(10) - meter(1)
meter(10) / meter(1)
meter(10) * meter(1)
```
Next we write the pair of methods for arithmetic with a meter and a number.
These are almost identical, but while `meter(10) / 2` makes sense, `2 / meter(10)` does not (and neither do addition and subtraction).
To support both doubles and integers as operands, we dispatch over `numeric` here instead of `double`.
```{r, error = TRUE}
vec_arith.vctrs_meter.numeric <- function(op, x, y, ...) {
switch(
op,
"/" = ,
"*" = new_meter(vec_arith_base(op, x, y)),
stop_incompatible_op(op, x, y)
)
}
vec_arith.numeric.vctrs_meter <- function(op, x, y, ...) {
switch(
op,
"*" = new_meter(vec_arith_base(op, x, y)),
stop_incompatible_op(op, x, y)
)
}
meter(2) * 10
meter(2) * as.integer(10)
10 * meter(2)
meter(20) / 10
10 / meter(20)
meter(20) + 10
```
For completeness, we also need `vec_arith.vctrs_meter.MISSING` for the unary `+` and `-` operators:
```{r}
vec_arith.vctrs_meter.MISSING <- function(op, x, y, ...) {
switch(op,
`-` = x * -1,
`+` = x,
stop_incompatible_op(op, x, y)
)
}
-meter(1)
+meter(1)
```
## Implementing a vctrs S3 class in a package
Defining S3 methods interactively is fine for iteration and exploration, but if your class lives in a package, you need to do a few more things:
- Register the S3 methods by listing them in the `NAMESPACE` file.
- Create documentation around your methods, for the sake of your user and to satisfy `R CMD check`.
Let's assume that the `percent` class is implemented in the pizza package in the file `R/percent.R`.
Here we walk through the major sections of this hypothetical file.
You've seen all of this code before, but now it's augmented by the roxygen2 directives that produce the correct `NAMESPACE` entries and help topics.
### Getting started
First, the pizza package needs to include vctrs in the `Imports` section of its `DESCRIPTION` (perhaps by calling `usethis::use_package("vctrs")`.
While vctrs is under very active development, it probably makes sense to state a minimum version.
Imports:
a_package,
another_package,
...
vctrs (>= x.y.z),
...
Then we make all vctrs functions available within the pizza package by including the directive `#' @import vctrs` somewhere.
Usually, it's not good practice to `@import` the entire namespace of a package, but vctrs is deliberately designed with this use case in mind.
Where should we put `#' @import vctrs`?
There are two natural locations:
- With package-level docs in `R/pizza-doc.R`.
You can use `usethis::use_package_doc()` to initiate this package-level documentation.
- In `R/percent.R`. This makes the most sense when the vctrs S3 class is a modest and self-contained part of the overall package.
We also must use one of these locations to dump some internal documentation that's needed to avoid `R CMD check` complaints.
We don't expect any human to ever read this documentation.
Here's how this dummy documentation should look, combined with the `#' @import vctrs` directive described above.
```{r eval = FALSE}
#' Internal vctrs methods
#'
#' @import vctrs
#' @keywords internal
#' @name pizza-vctrs
NULL
```
This should appear in `R/pizza-doc.R` (package-level docs) or in `R/percent.R` (class-focused file).
Remember to call `devtools::document()` regularly, as you develop, to regenerate `NAMESPACE` and the `.Rd` files.
From this point on, the code shown is expected to appear in `R/percent.R`.
### Low-level and user-friendly constructors
Next we add our constructor:
```{r}
new_percent <- function(x = double()) {
if (!is_double(x)) {
abort("`x` must be a double vector.")
}
new_vctr(x, class = "pizza_percent")
}
```
Note that the name of the package must be included in the class name (`pizza_percent`), but it does not need to be included in the constructor name.
You do not need to export the constructor, unless you want people to extend your class.
We can also add a call to `setOldClass()` for compatibility with S4:
```{r}
# for compatibility with the S4 system
methods::setOldClass(c("pizza_percent", "vctrs_vctr"))
```
Because we've used a function from the methods package, you'll also need to add methods to `Imports`, with (e.g.) `usethis::use_package("methods")`.
This is a "free" dependency because methods is bundled with every R install.
Next we implement, export, and document a user-friendly helper: `percent()`.
```{r}
#' `percent` vector
#'
#' This creates a double vector that represents percentages so when it is
#' printed, it is multiplied by 100 and suffixed with `%`.
#'
#' @param x A numeric vector
#' @return An S3 vector of class `pizza_percent`.
#' @export
#' @examples
#' percent(c(0.25, 0.5, 0.75))
percent <- function(x = double()) {
x <- vec_cast(x, double())
new_percent(x)
}
```
(Again note that the package name will appear in the class, but does not need to occur in the function, because we can already do `pizza::percent()`; it would be redundant to have `pizza::pizza_percent()`.)
### Other helpers
It's a good idea to provide a function that tests if an object is of this class.
If you do so, it makes sense to document it with the user-friendly constructor `percent()`:
```{r}
#' @export
#' @rdname percent
is_percent <- function(x) {
inherits(x, "pizza_percent")
}
```
You'll also need to update the `percent()` documentation to reflect that `x` now means two different things:
```{r}
#' @param x
#' * For `percent()`: A numeric vector
#' * For `is_percent()`: An object to test.
```
Next we provide the key methods to make printing work.
These are S3 methods, so they don't need to be documented, but they do need to be exported.
```{r eval = FALSE}
#' @export
format.pizza_percent <- function(x, ...) {
out <- formatC(signif(vec_data(x) * 100, 3))
out[is.na(x)] <- NA
out[!is.na(x)] <- paste0(out[!is.na(x)], "%")
out
}
#' @export
vec_ptype_abbr.pizza_percent <- function(x, ...) {
"prcnt"
}
```
Finally, we implement methods for `vec_ptype2()` and `vec_cast()`.
```{r, eval = FALSE}
#' @export
vec_ptype2.vctrs_percent.vctrs_percent <- function(x, y, ...) new_percent()
#' @export
vec_ptype2.double.vctrs_percent <- function(x, y, ...) double()
#' @export
vec_cast.pizza_percent.pizza_percent <- function(x, to, ...) x
#' @export
vec_cast.pizza_percent.double <- function(x, to, ...) percent(x)
#' @export
vec_cast.double.pizza_percent <- function(x, to, ...) vec_data(x)
```
### Arithmetic
Writing double dispatch methods for `vec_arith()` is currently more awkward than writing them for `vec_ptype2()` or `vec_cast()`.
We plan to improve this in the future.
For now, you can use the following instructions.
If you define a new type and want to write `vec_arith()` methods for it, you'll need to provide a new single dispatch S3 generic for it of the following form:
```{r, eval=FALSE}
#' @export
#' @method vec_arith my_type
vec_arith.my_type <- function(op, x, y, ...) {
UseMethod("vec_arith.my_type", y)
}
```
Note that this actually functions as both an S3 method for `vec_arith()` and an S3 generic called `vec_arith.my_type()` that dispatches off `y`.
roxygen2 only recognizes it as an S3 generic, so you have to register the S3 method part of this with an explicit `@method` call.
After that, you can define double dispatch methods, but you still need an explicit `@method` tag to ensure it is registered with the correct generic:
```{r, eval=FALSE}
#' @export
#' @method vec_arith.my_type my_type
vec_arith.my_type.my_type <- function(op, x, y, ...) {
# implementation here
}
#' @export
#' @method vec_arith.my_type integer
vec_arith.my_type.integer <- function(op, x, y, ...) {
# implementation here
}
#' @export
#' @method vec_arith.integer my_type
vec_arith.integer.my_type <- function(op, x, y, ...) {
# implementation here
}
```
vctrs provides the hybrid S3 generics/methods for most of the base R types, like `vec_arith.integer()`.
If you don't fully import vctrs with `@import vctrs`, then you will need to explicitly import the generic you are registering double dispatch methods for with `@importFrom vctrs vec_arith.integer`.
### Testing
It's good practice to test your new class.
Specific recommendations:
- `R/percent.R` is the type of file where you really do want 100% test coverage.
You can use `devtools::test_coverage_file()` to check this.
- Make sure to test behaviour with zero-length inputs and missing values.
- Use `testthat::verify_output()` to test your format method.
Customised printing is often a primary motivation for creating your own S3 class in the first place, so this will alert you to unexpected changes in your printed output.
Read more about `verify_output()` in the [testthat v2.3.0 blog post](https://www.tidyverse.org/blog/2019/11/testthat-2-3-0/); it's an example of a so-called [golden test](https://ro-che.info/articles/2017-12-04-golden-tests).
- Check for method symmetry; use `expect_s3_class()`, probably with `exact = TRUE`, to ensure that `vec_c(x, y)` and `vec_c(y, x)` return the same type of output for the important `x`s and `y`s in your domain.
- Use `testthat::expect_error()` to check that inputs that can't be combined fail with an error.
Here, you should be generally checking the class of the error, not its message.
Relevant classes include `vctrs_error_assert_ptype`, `vctrs_error_assert_size`, and `vctrs_error_incompatible_type`.
```{r, eval = FALSE}
expect_error(vec_c(1, "a"), class = "vctrs_error_incompatible_type")
```
If your tests pass when run by `devtools::test()`, but fail when run in `R CMD check`, it is very likely to reflect a problem with S3 method registration.
Carefully check your roxygen2 comments and the generated `NAMESPACE`.
### Existing classes
Before you build your own class, you might want to consider using, or subclassing existing classes.
You can check [awesome-vctrs](https://github.com/krlmlr/awesome-vctrs) for a curated list of R vector classes, some of which are built with vctrs.
If you've built or extended a class, consider adding it to that list so other people can use it.
|
/scratch/gouwar.j/cran-all/cranData/vctrs/inst/doc/s3-vector.Rmd
|
## ----include = FALSE----------------------------------------------------------
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
## ----setup--------------------------------------------------------------------
library(vctrs)
library(rlang)
library(zeallot)
## -----------------------------------------------------------------------------
vec_ptype_show(median(c(1L, 1L)))
vec_ptype_show(median(c(1L, 1L, 1L)))
## -----------------------------------------------------------------------------
vec_ptype_show(sapply(1L, function(x) c(x, x)))
vec_ptype_show(sapply(integer(), function(x) c(x, x)))
## -----------------------------------------------------------------------------
vec_ptype_show(c(NA, Sys.Date()))
vec_ptype_show(c(Sys.Date(), NA))
## -----------------------------------------------------------------------------
env <- new.env(parent = emptyenv())
length(env)
length(mean)
length(c(env, mean))
## -----------------------------------------------------------------------------
vec_ptype_show(ifelse(NA, 1L, 1L))
vec_ptype_show(ifelse(FALSE, 1L, 1L))
## -----------------------------------------------------------------------------
c(FALSE, 1L, 2.5)
## -----------------------------------------------------------------------------
vec_c(FALSE, 1L, 2.5)
## ----error = TRUE-------------------------------------------------------------
c(FALSE, "x")
vec_c(FALSE, "x")
c(FALSE, list(1))
vec_c(FALSE, list(1))
## -----------------------------------------------------------------------------
c(10.5, factor("x"))
## -----------------------------------------------------------------------------
c(mean, globalenv())
## ----error = TRUE-------------------------------------------------------------
c(getRversion(), "x")
c("x", getRversion())
## ----error = TRUE-------------------------------------------------------------
vec_c(mean, globalenv())
vec_c(Sys.Date(), factor("x"), "x")
## -----------------------------------------------------------------------------
fa <- factor("a")
fb <- factor("b")
c(fa, fb)
## -----------------------------------------------------------------------------
vec_c(fa, fb)
vec_c(fb, fa)
## -----------------------------------------------------------------------------
datetime_nz <- as.POSIXct("2020-01-01 09:00", tz = "Pacific/Auckland")
c(datetime_nz)
## -----------------------------------------------------------------------------
vec_c(datetime_nz)
## -----------------------------------------------------------------------------
datetime_local <- as.POSIXct("2020-01-01 09:00")
datetime_houston <- as.POSIXct("2020-01-01 09:00", tz = "US/Central")
vec_c(datetime_local, datetime_houston, datetime_nz)
vec_c(datetime_houston, datetime_nz)
vec_c(datetime_nz, datetime_houston)
## -----------------------------------------------------------------------------
date <- as.Date("2020-01-01")
datetime <- as.POSIXct("2020-01-01 09:00")
c(date, datetime)
c(datetime, date)
## -----------------------------------------------------------------------------
vec_c(date, datetime)
vec_c(date, datetime_nz)
## -----------------------------------------------------------------------------
c(NA, fa)
c(NA, date)
c(NA, datetime)
## -----------------------------------------------------------------------------
vec_c(NA, fa)
vec_c(NA, date)
vec_c(NA, datetime)
## -----------------------------------------------------------------------------
df1 <- data.frame(x = 1)
df2 <- data.frame(x = 2)
str(c(df1, df1))
## -----------------------------------------------------------------------------
vec_c(df1, df2)
## -----------------------------------------------------------------------------
m <- matrix(1:4, nrow = 2)
c(m, m)
vec_c(m, m)
## -----------------------------------------------------------------------------
c(m, 1)
vec_c(m, 1)
## ----eval = FALSE-------------------------------------------------------------
# vec_c <- function(...) {
# args <- compact(list2(...))
#
# ptype <- vec_ptype_common(!!!args)
# if (is.null(ptype))
# return(NULL)
#
# ns <- map_int(args, vec_size)
# out <- vec_init(ptype, sum(ns))
#
# pos <- 1
# for (i in seq_along(ns)) {
# n <- ns[[i]]
#
# x <- vec_cast(args[[i]], to = ptype)
# vec_slice(out, pos:(pos + n - 1)) <- x
# pos <- pos + n
# }
#
# out
# }
## -----------------------------------------------------------------------------
if_else <- function(test, yes, no) {
if (!is_logical(test)) {
abort("`test` must be a logical vector.")
}
c(yes, no) %<-% vec_cast_common(yes, no)
c(test, yes, no) %<-% vec_recycle_common(test, yes, no)
out <- vec_init(yes, vec_size(yes))
vec_slice(out, test) <- vec_slice(yes, test)
vec_slice(out, !test) <- vec_slice(no, !test)
out
}
x <- c(NA, 1:4)
if_else(x > 2, "small", "big")
if_else(x > 2, factor("small"), factor("big"))
if_else(x > 2, Sys.Date(), Sys.Date() + 7)
## -----------------------------------------------------------------------------
if_else(x > 2, data.frame(x = 1), data.frame(y = 2))
if_else(x > 2, matrix(1:10, ncol = 2), cbind(30, 30))
|
/scratch/gouwar.j/cran-all/cranData/vctrs/inst/doc/stability.R
|
---
title: "Type and size stability"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Type and size stability}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
```
This vignette introduces the ideas of type-stability and size-stability. If a function possesses these properties, it is substantially easier to reason about because to predict the "shape" of the output you only need to know the "shape"s of the inputs.
This work is partly motivated by a common pattern that I noticed when reviewing code: if I read the code (without running it!), and I can't predict the type of each variable, I feel very uneasy about the code. This sense is important because most unit tests explore typical inputs, rather than exhaustively testing the strange and unusual. Analysing the types (and size) of variables makes it possible to spot unpleasant edge cases.
```{r setup}
library(vctrs)
library(rlang)
library(zeallot)
```
## Definitions
We say a function is __type-stable__ iff:
1. You can predict the output type knowing only the input types.
1. The order of arguments in ... does not affect the output type.
Similarly, a function is __size-stable__ iff:
1. You can predict the output size knowing only the input sizes, or
there is a single numeric input that specifies the output size.
Very few base R functions are size-stable, so I'll also define a slightly weaker condition. I'll call a function __length-stable__ iff:
1. You can predict the output _length_ knowing only the input _lengths_, or
there is a single numeric input that specifies the output _length_.
(But note that length-stable is not a particularly robust definition because `length()` returns a value for things that are not vectors.)
We'll call functions that don't obey these principles __type-unstable__ and __size-unstable__ respectively.
On top of type- and size-stability it's also desirable to have a single set of rules that are applied consistently. We want one set of type-coercion and size-recycling rules that apply everywhere, not many sets of rules that apply to different functions.
The goal of these principles is to minimise cognitive overhead. Rather than having to memorise many special cases, you should be able to learn one set of principles and apply them again and again.
### Examples
To make these ideas concrete, let's apply them to a few base functions:
1. `mean()` is trivially type-stable and size-stable because it always returns
a double vector of length 1 (or it throws an error).
1. Surprisingly, `median()` is type-unstable:
```{r}
vec_ptype_show(median(c(1L, 1L)))
vec_ptype_show(median(c(1L, 1L, 1L)))
```
It is, however, size-stable, since it always returns a vector of length 1.
1. `sapply()` is type-unstable because you can't predict the output type only
knowing the input types:
```{r}
vec_ptype_show(sapply(1L, function(x) c(x, x)))
vec_ptype_show(sapply(integer(), function(x) c(x, x)))
```
It's not quite size-stable; `vec_size(sapply(x, f))` is `vec_size(x)`
for vectors but not for matrices (the output is transposed) or
data frames (it iterates over the columns).
1. `vapply()` is a type-stable version of `sapply()` because
`vec_ptype_show(vapply(x, fn, template))` is always `vec_ptype_show(template)`.
It is size-unstable for the same reasons as `sapply()`.
1. `c()` is type-unstable because `c(x, y)` doesn't always output the same type
as `c(y, x)`.
```{r}
vec_ptype_show(c(NA, Sys.Date()))
vec_ptype_show(c(Sys.Date(), NA))
```
`c()` is *almost always* length-stable because `length(c(x, y))`
*almost always* equals `length(x) + length(y)`. One common source of
instability here is dealing with non-vectors (see the later section
"Non-vectors"):
```{r}
env <- new.env(parent = emptyenv())
length(env)
length(mean)
length(c(env, mean))
```
1. `paste(x1, x2)` is length-stable because `length(paste(x1, x2))`
equals `max(length(x1), length(x2))`. However, it doesn't follow the usual
arithmetic recycling rules because `paste(1:2, 1:3)` doesn't generate
a warning.
1. `ifelse()` is length-stable because `length(ifelse(cond, true, false))`
is always `length(cond)`. `ifelse()` is type-unstable because the output
type depends on the value of `cond`:
```{r}
vec_ptype_show(ifelse(NA, 1L, 1L))
vec_ptype_show(ifelse(FALSE, 1L, 1L))
```
1. `read.csv(file)` is type-unstable and size-unstable because, while you know
it will return a data frame, you don't know what columns it will return or
how many rows it will have. Similarly, `df[[i]]` is not type-stable because
the result depends on the _value_ of `i`. There are many important
functions that can not be made type-stable or size-stable!
With this understanding of type- and size-stability in hand, we'll use them to analyse some base R functions in greater depth and then propose alternatives with better properties.
## `c()` and `vctrs::vec_c()`
In this section we'll compare and contrast `c()` and `vec_c()`. `vec_c()` is both type- and size-stable because it possesses the following invariants:
* `vec_ptype(vec_c(x, y))` equals `vec_ptype_common(x, y)`.
* `vec_size(vec_c(x, y))` equals `vec_size(x) + vec_size(y)`.
`c()` has another undesirable property in that it's not consistent with `unlist()`; i.e., `unlist(list(x, y))` does not always equal `c(x, y)`; i.e., base R has multiple sets of type-coercion rules. I won't consider this problem further here.
I have two goals here:
* To fully document the quirks of `c()`, hence motivating the development
of an alternative.
* To discuss non-obvious consequences of the type- and size-stability above.
### Atomic vectors
If we only consider atomic vectors, `c()` is type-stable because it uses a hierarchy of types: character > complex > double > integer > logical.
```{r}
c(FALSE, 1L, 2.5)
```
`vec_c()` obeys similar rules:
```{r}
vec_c(FALSE, 1L, 2.5)
```
But it does not automatically coerce to character vectors or lists:
```{r, error = TRUE}
c(FALSE, "x")
vec_c(FALSE, "x")
c(FALSE, list(1))
vec_c(FALSE, list(1))
```
### Incompatible vectors and non-vectors
In general, most base methods do not throw an error:
```{r}
c(10.5, factor("x"))
```
If the inputs aren't vectors, `c()` automatically puts them in a list:
```{r}
c(mean, globalenv())
```
For numeric versions, this depends on the order of inputs. Version first is an error, otherwise the input is wrapped in a list:
```{r, error = TRUE}
c(getRversion(), "x")
c("x", getRversion())
```
`vec_c()` throws an error if the inputs are not vectors or not automatically coercible:
```{r, error = TRUE}
vec_c(mean, globalenv())
vec_c(Sys.Date(), factor("x"), "x")
```
### Factors
Combining two factors returns an integer vector:
```{r}
fa <- factor("a")
fb <- factor("b")
c(fa, fb)
```
(This is documented in `c()` but is still undesirable.)
`vec_c()` returns a factor taking the union of the levels. This behaviour is motivated by pragmatics: there are many places in base R that automatically convert character vectors to factors, so enforcing stricter behaviour would be unnecessarily onerous. (This is backed up by experience with `dplyr::bind_rows()`, which is stricter and is a common source of user difficulty.)
```{r}
vec_c(fa, fb)
vec_c(fb, fa)
```
### Date-times
`c()` strips the time zone associated with date-times:
```{r}
datetime_nz <- as.POSIXct("2020-01-01 09:00", tz = "Pacific/Auckland")
c(datetime_nz)
```
This behaviour is documented in `?DateTimeClasses` but is the source of considerable user pain.
`vec_c()` preserves time zones:
```{r}
vec_c(datetime_nz)
```
What time zone should the output have if inputs have different time zones? One option would be to be strict and force the user to manually align all the time zones. However, this is onerous (particularly because there's no easy way to change the time zone in base R), so vctrs chooses to use the first non-local time zone:
```{r}
datetime_local <- as.POSIXct("2020-01-01 09:00")
datetime_houston <- as.POSIXct("2020-01-01 09:00", tz = "US/Central")
vec_c(datetime_local, datetime_houston, datetime_nz)
vec_c(datetime_houston, datetime_nz)
vec_c(datetime_nz, datetime_houston)
```
### Dates and date-times
Combining dates and date-times with `c()` gives silently incorrect results:
```{r}
date <- as.Date("2020-01-01")
datetime <- as.POSIXct("2020-01-01 09:00")
c(date, datetime)
c(datetime, date)
```
This behaviour arises because neither `c.Date()` nor `c.POSIXct()` check that all inputs are of the same type.
`vec_c()` uses a standard set of rules to avoid this problem. When you mix dates and date-times, vctrs returns a date-time and converts dates to date-times at midnight (in the timezone of the date-time).
```{r}
vec_c(date, datetime)
vec_c(date, datetime_nz)
```
### Missing values
If a missing value comes at the beginning of the inputs, `c()` falls back to the internal behaviour, which strips all attributes:
```{r}
c(NA, fa)
c(NA, date)
c(NA, datetime)
```
`vec_c()` takes a different approach treating a logical vector consisting only of `NA` as the `unspecified()` class which can be converted to any other 1d type:
```{r}
vec_c(NA, fa)
vec_c(NA, date)
vec_c(NA, datetime)
```
### Data frames
Because it is *almost always* length-stable, `c()` combines data frames column wise (into a list):
```{r}
df1 <- data.frame(x = 1)
df2 <- data.frame(x = 2)
str(c(df1, df1))
```
`vec_c()` is size-stable, which implies it will row-bind data frames:
```{r}
vec_c(df1, df2)
```
### Matrices and arrays
The same reasoning applies to matrices:
```{r}
m <- matrix(1:4, nrow = 2)
c(m, m)
vec_c(m, m)
```
One difference is that `vec_c()` will "broadcast" a vector to match the dimensions of a matrix:
```{r}
c(m, 1)
vec_c(m, 1)
```
### Implementation
The basic implementation of `vec_c()` is reasonably simple. We first figure out the properties of the output, i.e. the common type and total size, and then allocate it with `vec_init()`, and then insert each input into the correct place in the output.
```{r, eval = FALSE}
vec_c <- function(...) {
args <- compact(list2(...))
ptype <- vec_ptype_common(!!!args)
if (is.null(ptype))
return(NULL)
ns <- map_int(args, vec_size)
out <- vec_init(ptype, sum(ns))
pos <- 1
for (i in seq_along(ns)) {
n <- ns[[i]]
x <- vec_cast(args[[i]], to = ptype)
vec_slice(out, pos:(pos + n - 1)) <- x
pos <- pos + n
}
out
}
```
(The real `vec_c()` is a bit more complicated in order to handle inner and outer names).
## `ifelse()`
One of the functions that motivate the development of vctrs is `ifelse()`. It has the surprising property that the result value is "A vector of the same length and attributes (including dimensions and class) as `test`". To me, it seems more reasonable for the type of the output to be controlled by the type of the `yes` and `no` arguments.
In `dplyr::if_else()` I swung too far towards strictness: it throws an error if `yes` and `no` are not the same type. This is annoying in practice because it requires typed missing values (`NA_character_` etc), and because the checks are only on the class (not the full prototype), it's easy to create invalid output.
I found it much easier to understand what `ifelse()` _should_ do once I internalised the ideas of type- and size-stability:
* The first argument must be logical.
* `vec_ptype(if_else(test, yes, no))` equals
`vec_ptype_common(yes, no)`. Unlike `ifelse()` this implies
that `if_else()` must always evaluate both `yes` and `no` in order
to figure out the correct type. I think this is consistent with `&&` (scalar
operation, short circuits) and `&` (vectorised, evaluates both sides).
* `vec_size(if_else(test, yes, no))` equals
`vec_size_common(test, yes, no)`. I think the output could have the same
size as `test` (i.e., the same behaviour as `ifelse`), but I _think_
as a general rule that your inputs should either be mutually recycling
or not.
This leads to the following implementation:
```{r}
if_else <- function(test, yes, no) {
if (!is_logical(test)) {
abort("`test` must be a logical vector.")
}
c(yes, no) %<-% vec_cast_common(yes, no)
c(test, yes, no) %<-% vec_recycle_common(test, yes, no)
out <- vec_init(yes, vec_size(yes))
vec_slice(out, test) <- vec_slice(yes, test)
vec_slice(out, !test) <- vec_slice(no, !test)
out
}
x <- c(NA, 1:4)
if_else(x > 2, "small", "big")
if_else(x > 2, factor("small"), factor("big"))
if_else(x > 2, Sys.Date(), Sys.Date() + 7)
```
By using `vec_size()` and `vec_slice()`, this definition of `if_else()` automatically works with data.frames and matrices:
```{r}
if_else(x > 2, data.frame(x = 1), data.frame(y = 2))
if_else(x > 2, matrix(1:10, ncol = 2), cbind(30, 30))
```
|
/scratch/gouwar.j/cran-all/cranData/vctrs/inst/doc/stability.Rmd
|
## ----setup, include = FALSE---------------------------------------------------
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
## -----------------------------------------------------------------------------
library(vctrs)
## -----------------------------------------------------------------------------
vec_ptype_show(FALSE)
vec_ptype_show(1L)
vec_ptype_show(2.5)
vec_ptype_show("three")
vec_ptype_show(list(1, 2, 3))
## -----------------------------------------------------------------------------
vec_ptype_show(array(logical(), c(2, 3)))
vec_ptype_show(array(integer(), c(2, 3, 4)))
vec_ptype_show(array(character(), c(2, 3, 4, 5)))
## -----------------------------------------------------------------------------
vec_ptype_show(factor("a"))
vec_ptype_show(ordered("b"))
## -----------------------------------------------------------------------------
vec_ptype(factor("a"))
## -----------------------------------------------------------------------------
vec_ptype_show(Sys.Date())
vec_ptype_show(Sys.time())
vec_ptype_show(as.difftime(10, units = "mins"))
## -----------------------------------------------------------------------------
vec_ptype_show(data.frame(a = FALSE, b = 1L, c = 2.5, d = "x"))
## -----------------------------------------------------------------------------
df <- data.frame(x = FALSE)
df$y <- data.frame(a = 1L, b = 2.5)
vec_ptype_show(df)
## ----error = TRUE-------------------------------------------------------------
vec_ptype_show(logical(), integer(), double())
vec_ptype_show(logical(), character())
## -----------------------------------------------------------------------------
vec_ptype_show(
array(1, c(0, 1)),
array(1, c(0, 2))
)
vec_ptype_show(
array(1, c(0, 1)),
array(1, c(0, 3)),
array(1, c(0, 3, 4)),
array(1, c(0, 3, 4, 5))
)
## ----error = TRUE-------------------------------------------------------------
vec_ptype_show(
array(1, c(0, 2)),
array(1, c(0, 3))
)
## -----------------------------------------------------------------------------
fa <- factor("a")
fb <- factor("b")
levels(vec_ptype_common(fa, fb))
levels(vec_ptype_common(fb, fa))
## -----------------------------------------------------------------------------
vec_ptype_show(new_date(), new_datetime())
## -----------------------------------------------------------------------------
vec_ptype_show(
new_datetime(tzone = "US/Central"),
new_datetime(tzone = "Pacific/Auckland")
)
## -----------------------------------------------------------------------------
vec_ptype_show(
new_datetime(tzone = ""),
new_datetime(tzone = ""),
new_datetime(tzone = "Pacific/Auckland")
)
## -----------------------------------------------------------------------------
vec_ptype_show(
data.frame(x = FALSE),
data.frame(x = 1L),
data.frame(x = 2.5)
)
## -----------------------------------------------------------------------------
vec_ptype_show(data.frame(x = 1, y = 1), data.frame(y = 1, z = 1))
## -----------------------------------------------------------------------------
str(vec_cast_common(
FALSE,
1:5,
2.5
))
str(vec_cast_common(
factor("x"),
factor("y")
))
str(vec_cast_common(
data.frame(x = 1),
data.frame(y = 1:2)
))
## ----error = TRUE-------------------------------------------------------------
# Cast succeeds
vec_cast(c(1, 2), integer())
# Cast fails
vec_cast(c(1.5, 2.5), factor("a"))
## ----error = TRUE-------------------------------------------------------------
vec_cast(c(1.5, 2), integer())
## -----------------------------------------------------------------------------
allow_lossy_cast(
vec_cast(c(1.5, 2), integer())
)
## -----------------------------------------------------------------------------
allow_lossy_cast(
vec_cast(c(1.5, 2), integer()),
x_ptype = double(),
to_ptype = integer()
)
## -----------------------------------------------------------------------------
x <- sample(1:10)
df <- data.frame(x = x)
vec_slice(x, 5:6)
vec_slice(df, 5:6)
## -----------------------------------------------------------------------------
vec_size_common(1:3, 1:3, 1:3)
vec_size_common(1:10, 1)
vec_size_common(integer(), 1)
## ----echo = FALSE, fig.cap="Summary of vctrs recycling rules. X indicates an error"----
knitr::include_graphics("../man/figures/sizes-recycling.png", dpi = 300)
## -----------------------------------------------------------------------------
vec_recycle(1:3, 3)
vec_recycle(1, 10)
## -----------------------------------------------------------------------------
vec_recycle_common(1:3, 1:3)
vec_recycle_common(1:10, 1)
## -----------------------------------------------------------------------------
rep(1, 6) + 1
rep(1, 6) + 1:2
rep(1, 6) + 1:3
## -----------------------------------------------------------------------------
invisible(pmax(1:2, 1:3))
invisible(1:2 + 1:3)
invisible(cbind(1:2, 1:3))
## -----------------------------------------------------------------------------
length(atan2(1:3, 1:2))
length(paste(1:3, 1:2))
length(ifelse(1:3, 1:2, 1:2))
## ----error = TRUE-------------------------------------------------------------
data.frame(1:2, 1:3)
## ----error = TRUE-------------------------------------------------------------
# length-0 output
1:2 + integer()
atan2(1:2, integer())
pmax(1:2, integer())
# dropped
cbind(1:2, integer())
# recycled to length of first
ifelse(rep(TRUE, 4), integer(), character())
# preserved-ish
paste(1:2, integer())
# Errors
data.frame(1:2, integer())
|
/scratch/gouwar.j/cran-all/cranData/vctrs/inst/doc/type-size.R
|
---
title: "Prototypes and sizes"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Prototypes and sizes}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r setup, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
```
Rather than using `class()` and `length()`, vctrs has notions of prototype (`vec_ptype_show()`) and size (`vec_size()`). This vignette discusses the motivation for why these alternatives are necessary and connects their definitions to type coercion and the recycling rules.
Size and prototype are motivated by thinking about the optimal behaviour for `c()` and `rbind()`, particularly inspired by data frames with columns that are matrices or data frames.
```{r}
library(vctrs)
```
## Prototype
The idea of a prototype is to capture the metadata associated with a vector without capturing any data. Unfortunately, the `class()` of an object is inadequate for this purpose:
* The `class()` doesn't include attributes. Attributes are important because,
for example, they store the levels of a factor and the timezone of a
`POSIXct`. You cannot combine two factors or two `POSIXct`s without
thinking about the attributes.
* The `class()` of a matrix is "matrix" and doesn't include the type of the
underlying vector or the dimensionality.
Instead, vctrs takes advantage of R's vectorised nature and uses a __prototype__, a 0-observation slice of the vector (this is basically `x[0]` but with some subtleties we'll come back to later). This is a miniature version of the vector that contains all of the attributes but none of the data.
Conveniently, you can create many prototypes using existing base functions (e.g, `double()` and `factor(levels = c("a", "b"))`). vctrs provides a few helpers (e.g. `new_date()`, `new_datetime()`, and `new_duration()`) where the equivalents in base R are missing.
### Base prototypes
`vec_ptype()` creates a prototype from an existing object. However, many base vectors have uninformative printing methods for 0-length subsets, so vctrs also provides `vec_ptype_show()`, which prints the prototype in a friendly way (and returns nothing).
Using `vec_ptype_show()` allows us to see the prototypes base R classes:
* Atomic vectors have no attributes and just display the underlying `typeof()`:
```{r}
vec_ptype_show(FALSE)
vec_ptype_show(1L)
vec_ptype_show(2.5)
vec_ptype_show("three")
vec_ptype_show(list(1, 2, 3))
```
* The prototype of matrices and arrays include the base type and the
dimensions after the first:
```{r}
vec_ptype_show(array(logical(), c(2, 3)))
vec_ptype_show(array(integer(), c(2, 3, 4)))
vec_ptype_show(array(character(), c(2, 3, 4, 5)))
```
* The prototype of a factor includes its levels. Levels are a character vector,
which can be arbitrarily long, so the prototype just shows a hash. If the
hash of two factors is equal, it's highly likely that their levels are also
equal.
```{r}
vec_ptype_show(factor("a"))
vec_ptype_show(ordered("b"))
```
While `vec_ptype_show()` prints only the hash, the prototype object itself does
contain all levels:
```{r}
vec_ptype(factor("a"))
```
* Base R has three key date time classes: dates, date-times (`POSIXct`),
and durations (`difftime)`. Date-times have a timezone, and durations have
a unit.
```{r}
vec_ptype_show(Sys.Date())
vec_ptype_show(Sys.time())
vec_ptype_show(as.difftime(10, units = "mins"))
```
* Data frames have the most complex prototype: the prototype of a data frame
is the name and prototype of each column:
```{r}
vec_ptype_show(data.frame(a = FALSE, b = 1L, c = 2.5, d = "x"))
```
Data frames can have columns that are themselves data frames, making this
a "recursive" type:
```{r}
df <- data.frame(x = FALSE)
df$y <- data.frame(a = 1L, b = 2.5)
vec_ptype_show(df)
```
### Coercing to common type
It's often important to combine vectors with multiple types. vctrs provides a consistent set of rules for coercion, via `vec_ptype_common()`. `vec_ptype_common()` possesses the following invariants:
* `class(vec_ptype_common(x, y))` equals `class(vec_ptype_common(y, x))`.
* `class(vec_ptype_common(x, vec_ptype_common(y, z))` equals
`class(vec_ptype_common(vec_ptype_common(x, y), z))`.
* `vec_ptype_common(x, NULL) == vec_ptype(x)`.
i.e., `vec_ptype_common()` is both commutative and associative (with respect to class) and has an identity element, `NULL`; i.e., it's a __commutative monoid__. This means the underlying implementation is quite simple: we can find the common type of any number of objects by progressively finding the common type of pairs of objects.
Like with `vec_ptype()`, the easiest way to explore `vec_ptype_common()` is with `vec_ptype_show()`: when given multiple inputs, it will print their common prototype. (In other words: program with `vec_ptype_common()` but play with `vec_ptype_show()`.)
* The common type of atomic vectors is computed very similar to the rules of base
R, except that we do not coerce to character automatically:
```{r, error = TRUE}
vec_ptype_show(logical(), integer(), double())
vec_ptype_show(logical(), character())
```
* Matrices and arrays are automatically broadcast to higher dimensions:
```{r}
vec_ptype_show(
array(1, c(0, 1)),
array(1, c(0, 2))
)
vec_ptype_show(
array(1, c(0, 1)),
array(1, c(0, 3)),
array(1, c(0, 3, 4)),
array(1, c(0, 3, 4, 5))
)
```
Provided that the dimensions follow the vctrs recycling rules:
```{r, error = TRUE}
vec_ptype_show(
array(1, c(0, 2)),
array(1, c(0, 3))
)
```
* Factors combine levels in the order in which they appear.
```{r}
fa <- factor("a")
fb <- factor("b")
levels(vec_ptype_common(fa, fb))
levels(vec_ptype_common(fb, fa))
```
* Combining a date and date-time yields a date-time:
```{r}
vec_ptype_show(new_date(), new_datetime())
```
When combining two date times, the timezone is taken from the first input:
```{r}
vec_ptype_show(
new_datetime(tzone = "US/Central"),
new_datetime(tzone = "Pacific/Auckland")
)
```
Unless it's the local timezone, in which case any explicit time zone will
win:
```{r}
vec_ptype_show(
new_datetime(tzone = ""),
new_datetime(tzone = ""),
new_datetime(tzone = "Pacific/Auckland")
)
```
* The common type of two data frames is the common type of each column that
occurs in both data frames:
```{r}
vec_ptype_show(
data.frame(x = FALSE),
data.frame(x = 1L),
data.frame(x = 2.5)
)
```
And the union of the columns that only occur in one:
```{r}
vec_ptype_show(data.frame(x = 1, y = 1), data.frame(y = 1, z = 1))
```
Note that new columns are added on the right-hand side. This is consistent
with the way that factor levels and time zones are handled.
### Casting to specified type
`vec_ptype_common()` finds the common type of a set of vector. Typically, however, what you want is a set of vectors coerced to that common type. That's the job of `vec_cast_common()`:
```{r}
str(vec_cast_common(
FALSE,
1:5,
2.5
))
str(vec_cast_common(
factor("x"),
factor("y")
))
str(vec_cast_common(
data.frame(x = 1),
data.frame(y = 1:2)
))
```
Alternatively, you can cast to a specific prototype using `vec_cast()`:
```{r, error = TRUE}
# Cast succeeds
vec_cast(c(1, 2), integer())
# Cast fails
vec_cast(c(1.5, 2.5), factor("a"))
```
If a cast is possible in general (i.e., double -> integer), but information is lost for a specific input (e.g. 1.5 -> 1), it will generate an error.
```{r, error = TRUE}
vec_cast(c(1.5, 2), integer())
```
You can suppress the lossy cast errors with `allow_lossy_cast()`:
```{r}
allow_lossy_cast(
vec_cast(c(1.5, 2), integer())
)
```
This will suppress all lossy cast errors. Supply prototypes if you want to be specific about the type of lossy cast allowed:
```{r}
allow_lossy_cast(
vec_cast(c(1.5, 2), integer()),
x_ptype = double(),
to_ptype = integer()
)
```
The set of casts should not be more permissive than the set of coercions. This is not enforced but it is expected from classes to follow the rule and keep the coercion ecosystem sound.
## Size
`vec_size()` was motivated by the need to have an invariant that describes the number of "observations" in a data structure. This is particularly important for data frames, as it's useful to have some function such that `f(data.frame(x))` equals `f(x)`. No base function has this property:
* `length(data.frame(x))` equals `1` because the length of a data frame
is the number of columns.
* `nrow(data.frame(x))` does not equal `nrow(x)` because `nrow()` of a
vector is `NULL`.
* `NROW(data.frame(x))` equals `NROW(x)` for vector `x`, so is almost what
we want. But because `NROW()` is defined in terms of `length()`, it returns
a value for every object, even types that can't go in a data frame, e.g.
`data.frame(mean)` errors even though `NROW(mean)` is `1`.
We define `vec_size()` as follows:
* It is the length of 1d vectors.
* It is the number of rows of data frames, matrices, and arrays.
* It throws error for non vectors.
Given `vec_size()`, we can give a precise definition of a data frame: a data frame is a list of vectors where every vector has the same size. This has the desirable property of trivially supporting matrix and data frame columns.
### Slicing
`vec_slice()` is to `vec_size()` as `[` is to `length()`; i.e., it allows you to select observations regardless of the dimensionality of the underlying object. `vec_slice(x, i)` is equivalent to:
* `x[i]` when `x` is a vector.
* `x[i, , drop = FALSE]` when `x` is a data frame.
* `x[i, , , drop = FALSE]` when `x` is a 3d array.
```{r}
x <- sample(1:10)
df <- data.frame(x = x)
vec_slice(x, 5:6)
vec_slice(df, 5:6)
```
`vec_slice(data.frame(x), i)` equals `data.frame(vec_slice(x, i))` (modulo variable and row names).
Prototypes are generated with `vec_slice(x, 0L)`; given a prototype, you can initialize a vector of given size (filled with `NA`s) with `vec_init()`.
### Common sizes: recycling rules
Closely related to the definition of size are the __recycling rules__. The recycling rules determine the size of the output when two vectors of different sizes are combined. In vctrs, the recycling rules are encoded in `vec_size_common()`, which gives the common size of a set of vectors:
```{r}
vec_size_common(1:3, 1:3, 1:3)
vec_size_common(1:10, 1)
vec_size_common(integer(), 1)
```
vctrs obeys a stricter set of recycling rules than base R. Vectors of size 1 are recycled to any other size. All other size combinations will generate an error. This strictness prevents common mistakes like `dest == c("IAH", "HOU"))`, at the cost of occasionally requiring an explicit calls to `rep()`.
```{r, echo = FALSE, fig.cap="Summary of vctrs recycling rules. X indicates an error"}
knitr::include_graphics("../man/figures/sizes-recycling.png", dpi = 300)
```
You can apply the recycling rules in two ways:
* If you have a vector and desired size, use `vec_recycle()`:
```{r}
vec_recycle(1:3, 3)
vec_recycle(1, 10)
```
* If you have multiple vectors and you want to recycle them to the same
size, use `vec_recycle_common()`:
```{r}
vec_recycle_common(1:3, 1:3)
vec_recycle_common(1:10, 1)
```
## Appendix: recycling in base R
The recycling rules in base R are described in [The R Language Definition](https://cran.r-project.org/doc/manuals/r-release/R-lang.html#Recycling-rules) but are not implemented in a single function and thus are not applied consistently. Here, I give a brief overview of their most common realisation, as well as showing some of the exceptions.
Generally, in base R, when a pair of vectors is not the same length, the shorter vector is recycled to the same length as the longer:
```{r}
rep(1, 6) + 1
rep(1, 6) + 1:2
rep(1, 6) + 1:3
```
If the length of the longer vector is not an integer multiple of the length of the shorter, you usually get a warning:
```{r}
invisible(pmax(1:2, 1:3))
invisible(1:2 + 1:3)
invisible(cbind(1:2, 1:3))
```
But some functions recycle silently:
```{r}
length(atan2(1:3, 1:2))
length(paste(1:3, 1:2))
length(ifelse(1:3, 1:2, 1:2))
```
And `data.frame()` throws an error:
```{r, error = TRUE}
data.frame(1:2, 1:3)
```
The R language definition states that "any arithmetic operation involving a zero-length vector has a zero-length result". But outside of arithmetic, this rule is not consistently followed:
```{r, error = TRUE}
# length-0 output
1:2 + integer()
atan2(1:2, integer())
pmax(1:2, integer())
# dropped
cbind(1:2, integer())
# recycled to length of first
ifelse(rep(TRUE, 4), integer(), character())
# preserved-ish
paste(1:2, integer())
# Errors
data.frame(1:2, integer())
```
|
/scratch/gouwar.j/cran-all/cranData/vctrs/inst/doc/type-size.Rmd
|
```{r, child = "../setup.Rmd", include = FALSE}
```
```{r, include = FALSE}
old_warn_on_fallback <- options(`vctrs:::warn_on_fallback` = FALSE)
knitr_defer(options(old_warn_on_fallback))
```
This guide provides a practical recipe for implementing `vec_ptype2()` and `vec_cast()` methods for coercions of data frame subclasses. Related topics:
- For an overview of the coercion mechanism in vctrs, see [`?theory-faq-coercion`][theory-faq-coercion].
- For an example of implementing coercion methods for simple vectors, see [`?howto-faq-coercion`][howto-faq-coercion].
Coercion of data frames occurs when different data frame classes are combined in some way. The two main methods of combination are currently row-binding with [vec_rbind()] and col-binding with [vec_cbind()] (which are in turn used by a number of dplyr and tidyr functions). These functions take multiple data frame inputs and automatically coerce them to their common type.
vctrs is generally strict about the kind of automatic coercions that are performed when combining inputs. In the case of data frames we have decided to be a bit less strict for convenience. Instead of throwing an incompatible type error, we fall back to a base data frame or a tibble if we don't know how to combine two data frame subclasses. It is still a good idea to specify the proper coercion behaviour for your data frame subclasses as soon as possible.
We will see two examples in this guide. The first example is about a data frame subclass that has no particular attributes to manage. In the second example, we implement coercion methods for a tibble subclass that includes potentially incompatible attributes.
## Roxygen workflow
```{r, child = "snippet-roxy-workflow.Rmd"}
```
## Parent methods
Most of the common type determination should be performed by the parent class. In vctrs, double dispatch is implemented in such a way that you need to call the methods for the parent class manually. For `vec_ptype2()` this means you need to call `df_ptype2()` (for data frame subclasses) or `tib_ptype2()` (for tibble subclasses). Similarly, `df_cast()` and `tib_cast()` are the workhorses for `vec_cast()` methods of subtypes of `data.frame` and `tbl_df`. These functions take the union of the columns in `x` and `y`, and ensure shared columns have the same type.
These functions are much less strict than `vec_ptype2()` and `vec_cast()` as they accept any subclass of data frame as input. They always return a `data.frame` or a `tbl_df`. You will probably want to write similar functions for your subclass to avoid repetition in your code. You may want to export them as well if you are expecting other people to derive from your class.
## A `data.table` example
```{r, include = FALSE}
delayedAssign("as.data.table", {
if (is_installed("data.table")) {
env_get(ns_env("data.table"), "as.data.table")
} else {
function(...) abort("`data.table` must be installed.")
}
})
delayedAssign("data.table", {
if (is_installed("data.table")) {
env_get(ns_env("data.table"), "data.table")
} else {
function(...) abort("`data.table` must be installed.")
}
})
```
This example is the actual implementation of vctrs coercion methods for `data.table`. This is a simple example because we don't have to keep track of attributes for this class or manage incompatibilities. See the tibble section for a more complicated example.
We first create the `dt_ptype2()` and `dt_cast()` helpers. They wrap around the parent methods `df_ptype2()` and `df_cast()`, and transform the common type or converted input to a data table. You may want to export these helpers if you expect other packages to derive from your data frame class.
These helpers should always return data tables. To this end we use the conversion generic `as.data.table()`. Depending on the tools available for the particular class at hand, a constructor might be appropriate as well.
```{r}
dt_ptype2 <- function(x, y, ...) {
as.data.table(df_ptype2(x, y, ...))
}
dt_cast <- function(x, to, ...) {
as.data.table(df_cast(x, to, ...))
}
```
We start with the self-self method:
```{r}
#' @export
vec_ptype2.data.table.data.table <- function(x, y, ...) {
dt_ptype2(x, y, ...)
}
```
Between a data frame and a data table, we consider the richer type to be data table. This decision is not based on the value coverage of each data structures, but on the idea that data tables have richer behaviour. Since data tables are the richer type, we call `dt_type2()` from the `vec_ptype2()` method. It always returns a data table, no matter the order of arguments:
```{r}
#' @export
vec_ptype2.data.table.data.frame <- function(x, y, ...) {
dt_ptype2(x, y, ...)
}
#' @export
vec_ptype2.data.frame.data.table <- function(x, y, ...) {
dt_ptype2(x, y, ...)
}
```
The `vec_cast()` methods follow the same pattern, but note how the method for coercing to data frame uses `df_cast()` rather than `dt_cast()`.
Also, please note that for historical reasons, the order of the classes in the method name is in reverse order of the arguments in the function signature. The first class represents `to`, whereas the second class represents `x`.
```{r}
#' @export
vec_cast.data.table.data.table <- function(x, to, ...) {
dt_cast(x, to, ...)
}
#' @export
vec_cast.data.table.data.frame <- function(x, to, ...) {
# `x` is a data.frame to be converted to a data.table
dt_cast(x, to, ...)
}
#' @export
vec_cast.data.frame.data.table <- function(x, to, ...) {
# `x` is a data.table to be converted to a data.frame
df_cast(x, to, ...)
}
```
With these methods vctrs is now able to combine data tables with data frames:
```{r}
vec_cbind(data.frame(x = 1:3), data.table(y = "foo"))
```
## A tibble example
In this example we implement coercion methods for a tibble subclass that carries a colour as a scalar metadata:
```{r}
# User constructor
my_tibble <- function(colour = NULL, ...) {
new_my_tibble(tibble::tibble(...), colour = colour)
}
# Developer constructor
new_my_tibble <- function(x, colour = NULL) {
stopifnot(is.data.frame(x))
tibble::new_tibble(
x,
colour = colour,
class = "my_tibble",
nrow = nrow(x)
)
}
df_colour <- function(x) {
if (inherits(x, "my_tibble")) {
attr(x, "colour")
} else {
NULL
}
}
#'@export
print.my_tibble <- function(x, ...) {
cat(sprintf("<%s: %s>\n", class(x)[[1]], df_colour(x)))
cli::cat_line(format(x)[-1])
}
```
```{r, include = FALSE}
# Necessary because includeRmd() evaluated in a child of global
knitr_local_registration("base::print", "my_tibble")
```
This subclass is very simple. All it does is modify the header.
```{r}
red <- my_tibble("red", x = 1, y = 1:2)
red
red[2]
green <- my_tibble("green", z = TRUE)
green
```
Combinations do not work properly out of the box, instead vctrs falls back to a bare tibble:
```{r}
vec_rbind(red, tibble::tibble(x = 10:12))
```
Instead of falling back to a data frame, we would like to return a `<my_tibble>` when combined with a data frame or a tibble. Because this subclass has more metadata than normal data frames (it has a colour), it is a _supertype_ of tibble and data frame, i.e. it is the richer type. This is similar to how a grouped tibble is a more general type than a tibble or a data frame. Conceptually, the latter are pinned to a single constant group.
The coercion methods for data frames operate in two steps:
- They check for compatible subclass attributes. In our case the tibble colour has to be the same, or be undefined.
- They call their parent methods, in this case [tib_ptype2()] and [tib_cast()] because we have a subclass of tibble. This eventually calls the data frame methods [df_ptype2()] and [tib_ptype2()] which match the columns and their types.
This process should usually be wrapped in two functions to avoid repetition. Consider exporting these if you expect your class to be derived by other subclasses.
We first implement a helper to determine if two data frames have compatible colours. We use the `df_colour()` accessor which returns `NULL` when the data frame colour is undefined.
```{r}
has_compatible_colours <- function(x, y) {
x_colour <- df_colour(x) %||% df_colour(y)
y_colour <- df_colour(y) %||% x_colour
identical(x_colour, y_colour)
}
```
Next we implement the coercion helpers. If the colours are not compatible, we call `stop_incompatible_cast()` or `stop_incompatible_type()`. These strict coercion semantics are justified because in this class colour is a _data_ attribute. If it were a non essential _detail_ attribute, like the timezone in a datetime, we would just standardise it to the value of the left-hand side.
In simpler cases (like the data.table example), these methods do not need to take the arguments suffixed in `_arg`. Here we do need to take these arguments so we can pass them to the `stop_` functions when we detect an incompatibility. They also should be passed to the parent methods.
```{r}
#' @export
my_tib_cast <- function(x, to, ..., x_arg = "", to_arg = "") {
out <- tib_cast(x, to, ..., x_arg = x_arg, to_arg = to_arg)
if (!has_compatible_colours(x, to)) {
stop_incompatible_cast(
x,
to,
x_arg = x_arg,
to_arg = to_arg,
details = "Can't combine colours."
)
}
colour <- df_colour(x) %||% df_colour(to)
new_my_tibble(out, colour = colour)
}
#' @export
my_tib_ptype2 <- function(x, y, ..., x_arg = "", y_arg = "") {
out <- tib_ptype2(x, y, ..., x_arg = x_arg, y_arg = y_arg)
if (!has_compatible_colours(x, y)) {
stop_incompatible_type(
x,
y,
x_arg = x_arg,
y_arg = y_arg,
details = "Can't combine colours."
)
}
colour <- df_colour(x) %||% df_colour(y)
new_my_tibble(out, colour = colour)
}
```
Let's now implement the coercion methods, starting with the self-self methods.
```{r}
#' @export
vec_ptype2.my_tibble.my_tibble <- function(x, y, ...) {
my_tib_ptype2(x, y, ...)
}
#' @export
vec_cast.my_tibble.my_tibble <- function(x, to, ...) {
my_tib_cast(x, to, ...)
}
```
```{r, include = FALSE}
knitr_local_registration("vctrs::vec_ptype2", "my_tibble.my_tibble")
knitr_local_registration("vctrs::vec_cast", "my_tibble.my_tibble")
```
We can now combine compatible instances of our class!
```{r, error = TRUE}
vec_rbind(red, red)
vec_rbind(green, green)
vec_rbind(green, red)
```
The methods for combining our class with tibbles follow the same pattern. For ptype2 we return our class in both cases because it is the richer type:
```{r}
#' @export
vec_ptype2.my_tibble.tbl_df <- function(x, y, ...) {
my_tib_ptype2(x, y, ...)
}
#' @export
vec_ptype2.tbl_df.my_tibble <- function(x, y, ...) {
my_tib_ptype2(x, y, ...)
}
```
For cast are careful about returning a tibble when casting to a tibble. Note the call to `vctrs::tib_cast()`:
```{r}
#' @export
vec_cast.my_tibble.tbl_df <- function(x, to, ...) {
my_tib_cast(x, to, ...)
}
#' @export
vec_cast.tbl_df.my_tibble <- function(x, to, ...) {
tib_cast(x, to, ...)
}
```
```{r, include = FALSE}
knitr_local_registration("vctrs::vec_ptype2", "my_tibble.tbl_df")
knitr_local_registration("vctrs::vec_ptype2", "tbl_df.my_tibble")
knitr_local_registration("vctrs::vec_cast", "tbl_df.my_tibble")
knitr_local_registration("vctrs::vec_cast", "my_tibble.tbl_df")
```
From this point, we get correct combinations with tibbles:
```{r}
vec_rbind(red, tibble::tibble(x = 10:12))
```
However we are not done yet. Because the coercion hierarchy is different from the class hierarchy, there is no inheritance of coercion methods. We're not getting correct behaviour for data frames yet because we haven't explicitly specified the methods for this class:
```{r}
vec_rbind(red, data.frame(x = 10:12))
```
Let's finish up the boiler plate:
```{r}
#' @export
vec_ptype2.my_tibble.data.frame <- function(x, y, ...) {
my_tib_ptype2(x, y, ...)
}
#' @export
vec_ptype2.data.frame.my_tibble <- function(x, y, ...) {
my_tib_ptype2(x, y, ...)
}
#' @export
vec_cast.my_tibble.data.frame <- function(x, to, ...) {
my_tib_cast(x, to, ...)
}
#' @export
vec_cast.data.frame.my_tibble <- function(x, to, ...) {
df_cast(x, to, ...)
}
```
```{r, include = FALSE}
# Necessary because includeRmd() evaluated in a child of global
knitr_local_registration("vctrs::vec_ptype2", "my_tibble.data.frame")
knitr_local_registration("vctrs::vec_ptype2", "data.frame.my_tibble")
knitr_local_registration("vctrs::vec_cast", "my_tibble.data.frame")
knitr_local_registration("vctrs::vec_cast", "data.frame.my_tibble")
```
This completes the implementation:
```{r}
vec_rbind(red, data.frame(x = 10:12))
```
|
/scratch/gouwar.j/cran-all/cranData/vctrs/man/faq/developer/howto-coercion-data-frame.Rmd
|
```{r, child = "../setup.Rmd", include = FALSE}
```
```{r, include = FALSE}
old_warn_on_fallback <- options(`vctrs:::warn_on_fallback` = FALSE)
knitr_defer(options(old_warn_on_fallback))
```
This guide illustrates how to implement `vec_ptype2()` and `vec_cast()` methods for existing classes. Related topics:
- For an overview of how these generics work and their roles in vctrs, see [`?theory-faq-coercion`][theory-faq-coercion].
- For an example of implementing coercion methods for data frame subclasses, see [`?howto-faq-coercion-data-frame`][howto-faq-coercion-data-frame].
- For a tutorial about implementing vctrs classes from scratch, see `vignette("s3-vector")`
## The natural number class
We'll illustrate how to implement coercion methods with a simple class that represents natural numbers. In this scenario we have an existing class that already features a constructor and methods for `print()` and subset.
```{r}
#' @export
new_natural <- function(x) {
if (is.numeric(x) || is.logical(x)) {
stopifnot(is_whole(x))
x <- as.integer(x)
} else {
stop("Can't construct natural from unknown type.")
}
structure(x, class = "my_natural")
}
is_whole <- function(x) {
all(x %% 1 == 0 | is.na(x))
}
#' @export
print.my_natural <- function(x, ...) {
cat("<natural>\n")
x <- unclass(x)
NextMethod()
}
#' @export
`[.my_natural` <- function(x, i, ...) {
new_natural(NextMethod())
}
```
```{r, include = FALSE}
# Necessary because includeRmd() evaluated in a child of global
knitr_local_registration("base::print", "my_natural")
knitr_local_registration("base::[", "my_natural")
```
```{r}
new_natural(1:3)
new_natural(c(1, NA))
```
## Roxygen workflow
```{r, child = "snippet-roxy-workflow.Rmd"}
```
## Implementing `vec_ptype2()`
### The self-self method
The first method to implement is the one that signals that your class is compatible with itself:
```{r}
#' @export
vec_ptype2.my_natural.my_natural <- function(x, y, ...) {
x
}
vec_ptype2(new_natural(1), new_natural(2:3))
```
```{r, include = FALSE}
# Necessary because includeRmd() evaluated in a child of global
knitr_local_registration("vctrs::vec_ptype2", "my_natural.my_natural")
```
`vec_ptype2()` implements a fallback to try and be compatible with simple classes, so it may seem that you don't need to implement the self-self coercion method. However, you must implement it explicitly because this is how vctrs knows that a class that is implementing vctrs methods (for instance this disable fallbacks to `base::c()`). Also, it makes your class a bit more efficient.
### The parent and children methods
Our natural number class is conceptually a parent of `<logical>` and a child of `<integer>`, but the class is not compatible with logical, integer, or double vectors yet:
```{r, error = TRUE}
vec_ptype2(TRUE, new_natural(2:3))
vec_ptype2(new_natural(1), 2:3)
```
We'll specify the twin methods for each of these classes, returning the richer class in each case.
```{r}
#' @export
vec_ptype2.my_natural.logical <- function(x, y, ...) {
# The order of the classes in the method name follows the order of
# the arguments in the function signature, so `x` is the natural
# number and `y` is the logical
x
}
#' @export
vec_ptype2.logical.my_natural <- function(x, y, ...) {
# In this case `y` is the richer natural number
y
}
```
Between a natural number and an integer, the latter is the richer class:
```{r}
#' @export
vec_ptype2.my_natural.integer <- function(x, y, ...) {
y
}
#' @export
vec_ptype2.integer.my_natural <- function(x, y, ...) {
x
}
```
```{r, include = FALSE}
# Necessary because includeRmd() evaluated in a child of global
knitr_local_registration("vctrs::vec_ptype2", "my_natural.logical")
knitr_local_registration("vctrs::vec_ptype2", "my_natural.integer")
knitr_local_registration("vctrs::vec_ptype2", "integer.my_natural")
knitr_local_registration("vctrs::vec_ptype2", "logical.my_natural")
```
We no longer get common type errors for logical and integer:
```{r}
vec_ptype2(TRUE, new_natural(2:3))
vec_ptype2(new_natural(1), 2:3)
```
We are not done yet. Pairwise coercion methods must be implemented for all the connected nodes in the coercion hierarchy, which include double vectors further up. The coercion methods for grand-parent types must be implemented separately:
```{r}
#' @export
vec_ptype2.my_natural.double <- function(x, y, ...) {
y
}
#' @export
vec_ptype2.double.my_natural <- function(x, y, ...) {
x
}
```
```{r, include = FALSE}
# Necessary because includeRmd() evaluated in a child of global
knitr_local_registration("vctrs::vec_ptype2", "my_natural.double")
knitr_local_registration("vctrs::vec_ptype2", "double.my_natural")
```
### Incompatible attributes
Most of the time, inputs are incompatible because they have different classes for which no `vec_ptype2()` method is implemented. More rarely, inputs could be incompatible because of their attributes. In that case incompatibility is signalled by calling `stop_incompatible_type()`.
In the following example, we implement a self-self ptype2 method for a hypothetical subclass of `<factor>` that has stricter combination semantics. The method throws an error when the levels of the two factors are not compatible.
```{r, eval = FALSE}
#' @export
vec_ptype2.my_strict_factor.my_strict_factor <- function(x, y, ..., x_arg = "", y_arg = "") {
if (!setequal(levels(x), levels(y))) {
stop_incompatible_type(x, y, x_arg = x_arg, y_arg = y_arg)
}
x
}
```
Note how the methods need to take `x_arg` and `y_arg` parameters and pass them on to `stop_incompatible_type()`. These argument tags help create more informative error messages when the common type determination is for a column of a data frame. They are part of the generic signature but can usually be left out if not used.
## Implementing `vec_cast()`
Corresponding `vec_cast()` methods must be implemented for all `vec_ptype2()` methods. The general pattern is to convert the argument `x` to the type of `to`. The methods should validate the values in `x` and make sure they conform to the values of `to`.
Please note that for historical reasons, the order of the classes in the method name is in reverse order of the arguments in the function signature. The first class represents `to`, whereas the second class represents `x`.
The self-self method is easy in this case, it just returns the target input:
```{r}
#' @export
vec_cast.my_natural.my_natural <- function(x, to, ...) {
x
}
```
The other types need to be validated. We perform input validation in the `new_natural()` constructor, so that's a good fit for our `vec_cast()` implementations.
```{r}
#' @export
vec_cast.my_natural.logical <- function(x, to, ...) {
# The order of the classes in the method name is in reverse order
# of the arguments in the function signature, so `to` is the natural
# number and `x` is the logical
new_natural(x)
}
vec_cast.my_natural.integer <- function(x, to, ...) {
new_natural(x)
}
vec_cast.my_natural.double <- function(x, to, ...) {
new_natural(x)
}
```
```{r, include = FALSE}
# Necessary because includeRmd() evaluated in a child of global
knitr_local_registration("vctrs::vec_cast", "my_natural.my_natural")
knitr_local_registration("vctrs::vec_cast", "my_natural.logical")
knitr_local_registration("vctrs::vec_cast", "my_natural.integer")
knitr_local_registration("vctrs::vec_cast", "my_natural.double")
```
With these methods, vctrs is now able to combine logical and natural vectors. It properly returns the richer type of the two, a natural vector:
```{r}
vec_c(TRUE, new_natural(1), FALSE)
```
Because we haven't implemented conversions _from_ natural, it still doesn't know how to combine natural with the richer integer and double types:
```{r, error = TRUE}
vec_c(new_natural(1), 10L)
vec_c(1.5, new_natural(1))
```
This is quick work which completes the implementation of coercion methods for vctrs:
```{r}
#' @export
vec_cast.logical.my_natural <- function(x, to, ...) {
# In this case `to` is the logical and `x` is the natural number
attributes(x) <- NULL
as.logical(x)
}
#' @export
vec_cast.integer.my_natural <- function(x, to, ...) {
attributes(x) <- NULL
as.integer(x)
}
#' @export
vec_cast.double.my_natural <- function(x, to, ...) {
attributes(x) <- NULL
as.double(x)
}
```
```{r, include = FALSE}
# Necessary because includeRmd() evaluated in a child of global
knitr_local_registration("vctrs::vec_cast", "logical.my_natural")
knitr_local_registration("vctrs::vec_cast", "integer.my_natural")
knitr_local_registration("vctrs::vec_cast", "double.my_natural")
```
And we now get the expected combinations.
```{r}
vec_c(new_natural(1), 10L)
vec_c(1.5, new_natural(1))
```
|
/scratch/gouwar.j/cran-all/cranData/vctrs/man/faq/developer/howto-coercion.Rmd
|
```{r, child = "../setup.Rmd", include = FALSE}
```
```{r, include = FALSE}
stopifnot(rlang::is_installed("dplyr"))
```
The tidyverse is a bit stricter than base R regarding what kind of objects are considered as vectors (see the [user FAQ][faq-error-scalar-type] about this topic). Sometimes vctrs won't treat your class as a vector when it should.
## Why isn't my list class considered a vector?
By default, S3 lists are not considered to be vectors by vctrs:
```{r}
my_list <- structure(list(), class = "my_class")
vctrs::vec_is(my_list)
```
To be treated as a vector, the class must either inherit from `"list"` explicitly:
```{r}
my_explicit_list <- structure(list(), class = c("my_class", "list"))
vctrs::vec_is(my_explicit_list)
```
Or it should implement a `vec_proxy()` method that returns its input if explicit inheritance is not possible or troublesome:
```{r}
#' @export
vec_proxy.my_class <- function(x, ...) x
vctrs::vec_is(my_list)
```
Note that explicit inheritance is the preferred way because this makes it possible for your class to dispatch on `list` methods of S3 generics:
```{r, error = TRUE}
my_generic <- function(x) UseMethod("my_generic")
my_generic.list <- function(x) "dispatched!"
my_generic(my_list)
my_generic(my_explicit_list)
```
## Why isn't my data frame class considered a vector?
The most likely explanation is that the data frame has not been
properly constructed.
However, if you get an "Input must be a vector" error with a data frame subclass, it probably means that the data frame has not been properly constructed. The main cause of these errors are data frames whose _base class_ is not `"data.frame"`:
```{r, error = TRUE}
my_df <- data.frame(x = 1)
class(my_df) <- c("data.frame", "my_class")
vctrs::obj_check_vector(my_df)
```
This is problematic as many tidyverse functions won't work properly:
```{r, error = TRUE}
dplyr::slice(my_df, 1)
```
It is generally not appropriate to declare your class to be a superclass of another class. We generally consider this undefined behaviour (UB). To fix these errors, you can simply change the construction of your data frame class so that `"data.frame"` is a base class, i.e. it should come last in the class vector:
```{r}
class(my_df) <- c("my_class", "data.frame")
vctrs::obj_check_vector(my_df)
dplyr::slice(my_df, 1)
```
|
/scratch/gouwar.j/cran-all/cranData/vctrs/man/faq/developer/howto-faq-fix-scalar-type-error.Rmd
|
# Implementing coercion methods
- For an overview of how these generics work and their roles in vctrs, see [`?theory-faq-coercion`][theory-faq-coercion].
- For an example of implementing coercion methods for simple vectors, see [`?howto-faq-coercion`][howto-faq-coercion].
- For an example of implementing coercion methods for data frame subclasses, see [`?howto-faq-coercion-data-frame`][howto-faq-coercion-data-frame].
- For a tutorial about implementing vctrs classes from scratch, see `vignette("s3-vector")`.
|
/scratch/gouwar.j/cran-all/cranData/vctrs/man/faq/developer/links-coercion.Rmd
|
vctrs provides a framework for working with vector classes in a generic way. However, it implements several compatibility fallbacks to base R methods. In this reference you will find how vctrs tries to be compatible with your vector class, and what base methods you need to implement for compatibility.
If you're starting from scratch, we think you'll find it easier to start using [new_vctr()] as documented in `vignette("s3-vector")`. This guide is aimed for developers with existing vector classes.
## Aggregate operations with fallbacks
All vctrs operations are based on four primitive generics described in the next section. However there are many higher level operations. The most important ones implement fallbacks to base generics for maximum compatibility with existing classes.
- [vec_slice()] falls back to the base `[` generic if no [vec_proxy()] method is implemented. This way foreign classes that do not implement [vec_restore()] can restore attributes based on the new subsetted contents.
- [vec_c()] and [vec_rbind()] now fall back to [base::c()] if the inputs have a common parent class with a `c()` method (only if they have no self-to-self `vec_ptype2()` method).
vctrs works hard to make your `c()` method success in various situations (with `NULL` and `NA` inputs, even as first input which would normally prevent dispatch to your method). The main downside compared to using vctrs primitives is that you can't combine vectors of different classes since there is no extensible mechanism of coercion in `c()`, and it is less efficient in some cases.
## The vctrs primitives
Most functions in vctrs are aggregate operations: they call other vctrs functions which themselves call other vctrs functions. The dependencies of a vctrs functions are listed in the Dependencies section of its documentation page. Take a look at [vec_count()] for an example.
These dependencies form a tree whose leaves are the four vctrs primitives. Here is the diagram for `vec_count()`:
\\figure{vec-count-deps.png}
### The coercion generics
The coercion mechanism in vctrs is based on two generics:
- [vec_ptype2()]
- [vec_cast()]
See the [theory overview][theory-faq-coercion].
Two objects with the same class and the same attributes are always considered compatible by ptype2 and cast. If the attributes or classes differ, they throw an incompatible type error.
Coercion errors are the main source of incompatibility with vctrs. See the [howto guide][howto-faq-coercion] if you need to implement methods for these generics.
### The proxy and restoration generics
- [vec_proxy()]
- [vec_restore()]
These generics are essential for vctrs but mostly optional. `vec_proxy()` defaults to an [identity][identity] function and you normally don't need to implement it. The proxy a vector must be one of the atomic vector types, a list, or a data frame. By default, S3 lists that do not inherit from `"list"` do not have an identity proxy. In that case, you need to explicitly implement `vec_proxy()` or make your class inherit from list.
|
/scratch/gouwar.j/cran-all/cranData/vctrs/man/faq/developer/reference-compatibility.Rmd
|
To implement methods for generics, first import the generics in your namespace and redocument:
```{r, eval = FALSE}
#' @importFrom vctrs vec_ptype2 vec_cast
NULL
```
Note that for each batches of methods that you add to your package, you need to export the methods and redocument immediately, even during development. Otherwise they won't be in scope when you run unit tests e.g. with testthat.
Implementing double dispatch methods is very similar to implementing regular S3 methods. In these examples we are using roxygen2 tags to register the methods, but you can also register the methods manually in your NAMESPACE file or lazily with `s3_register()`.
|
/scratch/gouwar.j/cran-all/cranData/vctrs/man/faq/developer/snippet-roxy-workflow.Rmd
|
```{r, child = "../setup.Rmd", include = FALSE}
```
This is an overview of the usage of `vec_ptype2()` and `vec_cast()` and their role in the vctrs coercion mechanism. Related topics:
- For an example of implementing coercion methods for simple vectors, see [`?howto-faq-coercion`][howto-faq-coercion].
- For an example of implementing coercion methods for data frame subclasses, see [`?howto-faq-coercion-data-frame`][howto-faq-coercion-data-frame].
- For a tutorial about implementing vctrs classes from scratch, see `vignette("s3-vector")`.
## Combination mechanism in vctrs
The coercion system in vctrs is designed to make combination of multiple inputs consistent and extensible. Combinations occur in many places, such as row-binding, joins, subset-assignment, or grouped summary functions that use the split-apply-combine strategy. For example:
```{r, error = TRUE}
vec_c(TRUE, 1)
vec_c("a", 1)
vec_rbind(
data.frame(x = TRUE),
data.frame(x = 1, y = 2)
)
vec_rbind(
data.frame(x = "a"),
data.frame(x = 1, y = 2)
)
```
One major goal of vctrs is to provide a central place for implementing the coercion methods that make generic combinations possible. The two relevant generics are `vec_ptype2()` and `vec_cast()`. They both take two arguments and perform __double dispatch__, meaning that a method is selected based on the classes of both inputs.
The general mechanism for combining multiple inputs is:
1. Find the common type of a set of inputs by reducing (as in `base::Reduce()` or `purrr::reduce()`) the `vec_ptype2()` binary function over the set.
2. Convert all inputs to the common type with `vec_cast()`.
3. Initialise the output vector as an instance of this common type with `vec_init()`.
4. Fill the output vector with the elements of the inputs using `vec_assign()`.
The last two steps may require `vec_proxy()` and `vec_restore()` implementations, unless the attributes of your class are constant and do not depend on the contents of the vector. We focus here on the first two steps, which require `vec_ptype2()` and `vec_cast()` implementations.
## `vec_ptype2()`
Methods for `vec_ptype2()` are passed two _prototypes_, i.e. two inputs emptied of their elements. They implement two behaviours:
* If the types of their inputs are compatible, indicate which of them is the richer type by returning it. If the types are of equal resolution, return any of the two.
* Throw an error with `stop_incompatible_type()` when it can be determined from the attributes that the types of the inputs are not compatible.
### Type compatibility
A type is __compatible__ with another type if the values it represents are a subset or a superset of the values of the other type. The notion of "value" is to be interpreted at a high level, in particular it is not the same as the memory representation. For example, factors are represented in memory with integers but their values are more related to character vectors than to round numbers:
```{r, error = TRUE}
# Two factors are compatible
vec_ptype2(factor("a"), factor("b"))
# Factors are compatible with a character
vec_ptype2(factor("a"), "b")
# But they are incompatible with integers
vec_ptype2(factor("a"), 1L)
```
### Richness of type
Richness of type is not a very precise notion. It can be about richer data (for instance a `double` vector covers more values than an integer vector), richer behaviour (a `data.table` has richer behaviour than a `data.frame`), or both. If you have trouble determining which one of the two types is richer, it probably means they shouldn't be automatically coercible.
Let's look again at what happens when we combine a factor and a character:
```{r}
vec_ptype2(factor("a"), "b")
```
The ptype2 method for `<character>` and `<factor<"a">>` returns `<character>` because the former is a richer type. The factor can only contain `"a"` strings, whereas the character can contain any strings. In this sense, factors are a _subset_ of character.
Note that another valid behaviour would be to throw an incompatible type error. This is what a strict factor implementation would do. We have decided to be laxer in vctrs because it is easy to inadvertently create factors instead of character vectors, especially with older versions of R where `stringsAsFactors` is still true by default.
### Consistency and symmetry on permutation
Each ptype2 method should strive to have exactly the same behaviour when the inputs are permuted. This is not always possible, for example factor levels are aggregated in order:
```{r}
vec_ptype2(factor(c("a", "c")), factor("b"))
vec_ptype2(factor("b"), factor(c("a", "c")))
```
In any case, permuting the input should not return a fundamentally different type or introduce an incompatible type error.
### Coercion hierarchy
The classes that you can coerce together form a coercion (or subtyping) hierarchy. Below is a schema of the hierarchy for the base types like integer and factor. In this diagram the directions of the arrows express which type is richer. They flow from the bottom (more constrained types) to the top (richer types).
\\figure{coerce.png}
A coercion hierarchy is distinct from the structural hierarchy implied by memory types and classes. For instance, in a structural hierarchy, factors are built on top of integers. But in the coercion hierarchy they are more related to character vectors. Similarly, subclasses are not necessarily coercible with their superclasses because the coercion and structural hierarchies are separate.
### Implementing a coercion hierarchy
As a class implementor, you have two options. The simplest is to create an entirely separate hierarchy. The date and date-time classes are an example of an S3-based hierarchy that is completely separate. Alternatively, you can integrate your class in an existing hierarchy, typically by adding parent nodes on top of the hierarchy (your class is richer), by adding children node at the root of the hierarchy (your class is more constrained), or by inserting a node in the tree.
These coercion hierarchies are _implicit_, in the sense that they are implied by the `vec_ptype2()` implementations. There is no structured way to create or modify a hierarchy, instead you need to implement the appropriate coercion methods for all the types in your hierarchy, and diligently return the richer type in each case. The `vec_ptype2()` implementations are not transitive nor inherited, so all pairwise methods between classes lying on a given path must be implemented manually. This is something we might make easier in the future.
## `vec_cast()`
The second generic, `vec_cast()`, is the one that looks at the data and actually performs the conversion. Because it has access to more information than `vec_ptype2()`, it may be stricter and cause an error in more cases. `vec_cast()` has three possible behaviours:
- Determine that the prototypes of the two inputs are not compatible. This must be decided in exactly the same way as for `vec_ptype2()`. Call `stop_incompatible_cast()` if you can determine from the attributes that the types are not compatible.
- Detect incompatible values. Usually this is because the target type is too restricted for the values supported by the input type. For example, a fractional number can't be converted to an integer. The method should throw an error in that case.
- Return the input vector converted to the target type if all values are compatible. Whereas `vec_ptype2()` must return the same type when the inputs are permuted, `vec_cast()` is _directional_. It always returns the type of the right-hand side, or dies trying.
## Double dispatch
The dispatch mechanism for `vec_ptype2()` and `vec_cast()` looks like S3 but is actually a custom mechanism. Compared to S3, it has the following differences:
* It dispatches on the classes of the first two inputs.
* There is no inheritance of ptype2 and cast methods. This is because the S3 class hierarchy is not necessarily the same as the coercion hierarchy.
* `NextMethod()` does not work. Parent methods must be called explicitly if necessary.
* The default method is hard-coded.
## Data frames
The determination of the common type of data frames with `vec_ptype2()` happens in three steps:
1. Match the columns of the two input data frames. If some columns don't exist, they are created and filled with adequately typed `NA` values.
2. Find the common type for each column by calling `vec_ptype2()` on each pair of matched columns.
3. Find the common data frame type. For example the common type of a grouped tibble and a tibble is a grouped tibble because the latter is the richer type. The common type of a data table and a data frame is a data table.
`vec_cast()` operates similarly. If a data frame is cast to a target type that has fewer columns, this is an error.
If you are implementing coercion methods for data frames, you will need to explicitly call the parent methods that perform the common type determination or the type conversion described above. These are exported as [df_ptype2()] and [df_cast()].
### Data frame fallbacks
Being too strict with data frame combinations would cause too much pain because there are many data frame subclasses in the wild that don't implement vctrs methods. We have decided to implement a special fallback behaviour for foreign data frames. Incompatible data frames fall back to a base data frame:
```{r}
df1 <- data.frame(x = 1)
df2 <- structure(df1, class = c("foreign_df", "data.frame"))
vec_rbind(df1, df2)
```
When a tibble is involved, we fall back to tibble:
```{r}
df3 <- tibble::as_tibble(df1)
vec_rbind(df1, df3)
```
These fallbacks are not ideal but they make sense because all data frames share a common data structure. This is not generally the case for vectors. For example factors and characters have different representations, and it is not possible to find a fallback time mechanically.
However this fallback has a big downside: implementing vctrs methods for your data frame subclass is a breaking behaviour change. The proper coercion behaviour for your data frame class should be specified as soon as possible to limit the consequences of changing the behaviour of your class in R scripts.
|
/scratch/gouwar.j/cran-all/cranData/vctrs/man/faq/developer/theory-coercion.Rmd
|
```{r, child = "../setup.Rmd", include = FALSE}
```
Recycling describes the concept of repeating elements of one vector to match the size of another. There are two rules that underlie the "tidyverse" recycling rules:
- Vectors of size 1 will be recycled to the size of any other vector
- Otherwise, all vectors must have the same size
# Examples
```{r, warning = FALSE, message = FALSE, include = FALSE}
library(tibble)
```
Vectors of size 1 are recycled to the size of any other vector:
```{r}
tibble(x = 1:3, y = 1L)
```
This includes vectors of size 0:
```{r}
tibble(x = integer(), y = 1L)
```
If vectors aren't size 1, they must all be the same size. Otherwise, an error is thrown:
```{r, error = TRUE}
tibble(x = 1:3, y = 4:7)
```
# vctrs backend
Packages in r-lib and the tidyverse generally use [vec_size_common()] and [vec_recycle_common()] as the backends for handling recycling rules.
- `vec_size_common()` returns the common size of multiple vectors, after applying the recycling rules
- `vec_recycle_common()` goes one step further, and actually recycles the vectors to their common size
```{r, error = TRUE}
vec_size_common(1:3, "x")
vec_recycle_common(1:3, "x")
vec_size_common(1:3, c("x", "y"))
```
# Base R recycling rules
The recycling rules described here are stricter than the ones generally used by base R, which are:
- If any vector is length 0, the output will be length 0
- Otherwise, the output will be length `max(length_x, length_y)`, and a warning will be thrown if the length of the longer vector is not an integer multiple of the length of the shorter vector.
We explore the base R rules in detail in `vignette("type-size")`.
|
/scratch/gouwar.j/cran-all/cranData/vctrs/man/faq/developer/theory-recycling.Rmd
|
---
output: html_document
editor_options:
chunk_output_type: console
---
```{r, child = "../setup.Rmd", include = FALSE}
```
`vec_locate_matches()` is similar to `vec_match()`, but detects _all_ matches by default, and can match on conditions other than equality (like `>=` and `<`). There are also various other arguments to limit or adjust exactly which kinds of matches are returned. Here is an example:
```{r}
x <- c("a", "b", "a", "c", "d")
y <- c("d", "b", "a", "d", "a", "e")
# For each value of `x`, find all matches in `y`
# - The "c" in `x` doesn't have a match, so it gets an NA location by default
# - The "e" in `y` isn't matched by anything in `x`, so it is dropped by default
vec_locate_matches(x, y)
```
# Algorithm description
## Overview and `==`
The simplest (approximate) way to think about the algorithm that `df_locate_matches_recurse()` uses is that it sorts both inputs, and then starts at the midpoint in `needles` and uses a binary search to find each needle in `haystack`. Since there might be multiple of the same needle, we find the location of the lower and upper duplicate of that needle to handle all duplicates of that needle at once. Similarly, if there are duplicates of a matching `haystack` value, we find the lower and upper duplicates of the match.
If the condition is `==`, that is pretty much all we have to do. For each needle, we then record 3 things: the location of the needle, the location of the lower match in the haystack, and the match size (i.e. `loc_upper_match - loc_lower_match + 1`). This later gets expanded in `expand_compact_indices()` into the actual output.
After recording the matches for a single needle, we perform the same procedure on the LHS and RHS of that needle (remember we started on the midpoint needle). i.e. from `[1, loc_needle-1]` and `[loc_needle+1, size_needles]`, again taking the midpoint of those two ranges, finding their respective needle in the haystack, recording matches, and continuing on to the next needle. This iteration proceeds until we run out of needles.
When we have a data frame with multiple columns, we add a layer of recursion to this. For the first column, we find the locations of the lower/upper duplicate of the current needle, and we find the locations of the lower/upper matches in the haystack. If we are on the final column in the data frame, we record the matches, otherwise we pass this information on to another call to `df_locate_matches_recurse()`, bumping the column index and using these refined lower/upper bounds as the starting bounds for the next column.
I think an example would be useful here, so below I step through this process for a few iterations:
```{r}
# these are sorted already for simplicity
needles <- data_frame(x = c(1, 1, 2, 2, 2, 3), y = c(1, 2, 3, 4, 5, 3))
haystack <- data_frame(x = c(1, 1, 2, 2, 3), y = c(2, 3, 4, 4, 1))
needles
haystack
## Column 1, iteration 1
# start at midpoint in needles
# this corresponds to x==2
loc_mid_needles <- 3L
# finding all x==2 values in needles gives us:
loc_lower_duplicate_needles <- 3L
loc_upper_duplicate_needles <- 5L
# finding matches in haystack give us:
loc_lower_match_haystack <- 3L
loc_upper_match_haystack <- 4L
# compute LHS/RHS bounds for next needle
lhs_loc_lower_bound_needles <- 1L # original lower bound
lhs_loc_upper_bound_needles <- 2L # lower_duplicate-1
rhs_loc_lower_bound_needles <- 6L # upper_duplicate+1
rhs_loc_upper_bound_needles <- 6L # original upper bound
# We still have a 2nd column to check. So recurse and pass on the current
# duplicate and match bounds to start the 2nd column with.
## Column 2, iteration 1
# midpoint of [3, 5]
# value y==4
loc_mid_needles <- 4L
loc_lower_duplicate_needles <- 4L
loc_upper_duplicate_needles <- 4L
loc_lower_match_haystack <- 3L
loc_upper_match_haystack <- 4L
# last column, so record matches
# - this was location 4 in needles
# - lower match in haystack is at loc 3
# - match size is 2
# Now handle LHS and RHS of needle midpoint
lhs_loc_lower_bound_needles <- 3L # original lower bound
lhs_loc_upper_bound_needles <- 3L # lower_duplicate-1
rhs_loc_lower_bound_needles <- 5L # upper_duplicate+1
rhs_loc_upper_bound_needles <- 5L # original upper bound
## Column 2, iteration 2 (using LHS bounds)
# midpoint of [3,3]
# value of y==3
loc_mid_needles <- 3L
loc_lower_duplicate_needles <- 3L
loc_upper_duplicate_needles <- 3L
# no match! no y==3 in haystack for x==2
# lower-match will always end up > upper-match in this case
loc_lower_match_haystack <- 3L
loc_upper_match_haystack <- 2L
# no LHS or RHS needle values to do, so we are done here
## Column 2, iteration 3 (using RHS bounds)
# same as above, range of [5,5], value of y==5, which has no match in haystack
## Column 1, iteration 2 (LHS of first x needle)
# Now we are done with the x needles from [3,5], so move on to the LHS and RHS
# of that. Here we would do the LHS:
# midpoint of [1,2]
loc_mid_needles <- 1L
# ...
## Column 1, iteration 3 (RHS of first x needle)
# midpoint of [6,6]
loc_mid_needles <- 6L
# ...
```
In the real code, rather than comparing the double values of the columns directly, we replace each column with pseudo "joint ranks" computed between the i-th column of `needles` and the i-th column of `haystack`. It is approximately like doing `vec_rank(vec_c(needles$x, haystack$x), type = "dense")`, then splitting the resulting ranks back up into their corresponding needle/haystack columns. This keeps the recursion code simpler, because we only have to worry about comparing integers.
## Non-equi conditions and containers
At this point we can talk about non-equi conditions like `<` or `>=`. The general idea is pretty simple, and just builds on the above algorithm. For example, start with the `x` column from needles/haystack above:
```{r}
needles$x
haystack$x
```
If we used a condition of `<=`, then we'd do everything the same as before:
- Midpoint in needles is location 3, value `x==2`
- Find lower/upper duplicates in needles, giving locations `[3, 5]`
- Find lower/upper _exact_ match in haystack, giving locations `[3, 4]`
At this point, we need to "adjust" the `haystack` match bounds to account for the condition. Since `haystack` is ordered, our "rule" for `<=` is to keep the lower match location the same, but extend the upper match location to the upper bound, so we end up with `[3, 5]`. We know we can extend the upper match location because every haystack value after the exact match should be less than the needle. Then we just record the matches and continue on normally.
This approach is really nice, because we only have to exactly match the `needle` in `haystack`. We don't have to compare each needle against every value in `haystack`, which would take a massive amount of time.
However, it gets slightly more complex with data frames with multiple columns. Let's go back to our original `needles` and `haystack` data frames and apply the condition `<=` to each column. Here is another worked example, which shows a case where our "rule" falls apart on the second column.
```{r}
needles
haystack
# `condition = c("<=", "<=")`
## Column 1, iteration 1
# x == 2
loc_mid_needles <- 3L
loc_lower_duplicate_needles <- 3L
loc_upper_duplicate_needles <- 5L
# finding exact matches in haystack give us:
loc_lower_match_haystack <- 3L
loc_upper_match_haystack <- 4L
# because haystack is ordered we know we can expand the upper bound automatically
# to include everything past the match. i.e. needle of x==2 must be less than
# the haystack value at loc 5, which we can check by seeing that it is x==3.
loc_lower_match_haystack <- 3L
loc_upper_match_haystack <- 5L
## Column 2, iteration 1
# needles range of [3, 5]
# y == 4
loc_mid_needles <- 4L
loc_lower_duplicate_needles <- 4L
loc_upper_duplicate_needles <- 4L
# finding exact matches in haystack give us:
loc_lower_match_haystack <- 3L
loc_upper_match_haystack <- 4L
# lets try using our rule, which tells us we should be able to extend the upper
# bound:
loc_lower_match_haystack <- 3L
loc_upper_match_haystack <- 5L
# but the haystack value of y at location 5 is y==1, which is not less than y==4
# in the needles! looks like our rule failed us.
```
If you read through the above example, you'll see that the rule didn't work here. The problem is that while `haystack` is ordered (by `vec_order()`s standards), each column isn't ordered _independently_ of the others. Instead, each column is ordered within the "group" created by previous columns. Concretely, `haystack` here has an ordered `x` column, but if you look at `haystack$y` by itself, it isn't ordered (because of that 1 at the end). That is what causes the rule to fail.
```{r}
haystack
```
To fix this, we need to create haystack "containers" where the values within each container are all _totally_ ordered. For `haystack` that would create 2 containers and look like:
``` r
haystack[1:4,]
#> # A tibble: 4 × 2
#> x y
#> <dbl> <dbl>
#> 1 1 2
#> 2 1 3
#> 3 2 4
#> 4 2 4
haystack[5,]
#> # A tibble: 1 × 2
#> x y
#> <dbl> <dbl>
#> 1 3 1
```
This is essentially what `computing_nesting_container_ids()` does. You can actually see these ids with the helper, `compute_nesting_container_info()`:
```{r}
haystack2 <- haystack
# we really pass along the integer ranks, but in this case that is equivalent
# to converting our double columns to integers
haystack2$x <- as.integer(haystack2$x)
haystack2$y <- as.integer(haystack2$y)
info <- compute_nesting_container_info(haystack2, condition = c("<=", "<="))
# the ids are in the second slot.
# container ids break haystack into [1, 4] and [5, 5].
info[[2]]
```
So the idea is that for each needle, we look in each haystack container and find all the matches, then we aggregate all of the matches once at the end. `df_locate_matches_with_containers()` has the job of iterating over the containers.
Computing totally ordered containers can be expensive, but luckily it doesn't happen very often in normal usage.
- If there are all `==` conditions, we don't need containers (i.e. any equi join)
- If there is only 1 non-equi condition and no conditions after it, we don't need containers (i.e. most rolling joins)
- Otherwise the typical case where we need containers is if we have something like `date >= lower, date <= upper`. Even so, the computation cost generally scales with the number of columns in `haystack` you compute containers with (here 2), and it only really slows down around 4 columns or so, which I haven't ever seen a real life example of.
|
/scratch/gouwar.j/cran-all/cranData/vctrs/man/faq/internal/matches-algorithm.Rmd
|
```{r, child = "../setup.Rmd", include = FALSE}
```
## Promotion monoid
Promotions (i.e. automatic coercions) should always transform inputs to their richer type to avoid losing values of precision. `vec_ptype2()` returns the _richer_ type of two vectors, or throws an incompatible type error if none of the two vector types include the other. For example, the richer type of integer and double is the latter because double covers a larger range of values than integer.
`vec_ptype2()` is a [monoid](https://en.wikipedia.org/wiki/Monoid) over vectors, which in practical terms means that it is a well behaved operation for [reduction](https://purrr.tidyverse.org/reference/reduce.html). Reduction is an important operation for promotions because that is how the richer type of multiple elements is computed. As a monoid, `vec_ptype2()` needs an identity element, i.e. a value that doesn't change the result of the reduction. vctrs has two identity values, `NULL` and __unspecified__ vectors.
## The `NULL` identity
As an identity element that shouldn't influence the determination of the common type of a set of vectors, `NULL` is promoted to any type:
```{r}
vec_ptype2(NULL, "")
vec_ptype2(1L, NULL)
```
The common type of `NULL` and `NULL` is the identity `NULL`:
```{r}
vec_ptype2(NULL, NULL)
```
This way the result of `vec_ptype2(NULL, NULL)` does not influence subsequent promotions:
```{r}
vec_ptype2(
vec_ptype2(NULL, NULL),
""
)
```
## Unspecified vectors
In the vctrs coercion system, logical vectors of missing values are also automatically promoted to the type of any other vector, just like `NULL`. We call these vectors unspecified. The special coercion semantics of unspecified vectors serve two purposes:
1. It makes it possible to assign vectors of `NA` inside any type of vectors, even when they are not coercible with logical:
```{r}
x <- letters[1:5]
vec_assign(x, 1:2, c(NA, NA))
```
2. We can't put `NULL` in a data frame, so we need an identity element that behaves more like a vector. Logical vectors of `NA` seem a natural fit for this.
Unspecified vectors are thus promoted to any other type, just like `NULL`:
```{r}
vec_ptype2(NA, "")
vec_ptype2(1L, c(NA, NA))
```
## Finalising common types
vctrs has an internal vector type of class `vctrs_unspecified`. Users normally don't see such vectors in the wild, but they do come up when taking the common type of an unspecified vector with another identity value:
```{r}
vec_ptype2(NA, NA)
vec_ptype2(NA, NULL)
vec_ptype2(NULL, NA)
```
We can't return `NA` here because `vec_ptype2()` normally returns empty vectors. We also can't return `NULL` because unspecified vectors need to be recognised as logical vectors if they haven't been promoted at the end of the reduction.
```{r}
vec_ptype_finalise(vec_ptype2(NULL, NA))
```
See the output of `vec_ptype_common()` which performs the reduction and finalises the type, ready to be used by the caller:
```{r}
vec_ptype_common(NULL, NULL)
vec_ptype_common(NA, NULL)
```
Note that __partial__ types in vctrs make use of the same mechanism. They are finalised with `vec_ptype_finalise()`.
|
/scratch/gouwar.j/cran-all/cranData/vctrs/man/faq/internal/ptype2-identity.Rmd
|
```{r, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
options(
cli.unicode = FALSE,
rlang_call_format_srcrefs = FALSE
)
library(vctrs)
```
|
/scratch/gouwar.j/cran-all/cranData/vctrs/man/faq/setup.Rmd
|
```{r, child = "../setup.Rmd", include = FALSE}
```
```{r, include = FALSE}
stopifnot(rlang::is_installed("dplyr"))
```
Two vectors are __compatible__ when you can safely:
- Combine them into one larger vector.
- Assign values from one of the vectors into the other vector.
Examples of compatible types are integer and double vectors. On the other hand, integer and character vectors are not compatible.
# Common type of multiple vectors
There are two possible outcomes when multiple vectors of different types are combined into a larger vector:
- An incompatible type error is thrown because some of the types are not compatible:
```{r, error = TRUE}
df1 <- data.frame(x = 1:3)
df2 <- data.frame(x = "foo")
dplyr::bind_rows(df1, df2)
```
- The vectors are combined into a vector that has the common type of all inputs. In this example, the common type of integer and logical is integer:
```{r}
df1 <- data.frame(x = 1:3)
df2 <- data.frame(x = FALSE)
dplyr::bind_rows(df1, df2)
```
In general, the common type is the _richer_ type, in other words the type that can represent the most values. Logical vectors are at the bottom of the hierarchy of numeric types because they can only represent two values (not counting missing values). Then come integer vectors, and then doubles. Here is the vctrs type hierarchy for the fundamental vectors:
\\figure{coerce.png}
# Type conversion and lossy cast errors
Type compatibility does not necessarily mean that you can __convert__ one type to the other type. That's because one of the types might support a larger set of possible values. For instance, integer and double vectors are compatible, but double vectors can't be converted to integer if they contain fractional values.
When vctrs can't convert a vector because the target type is not as rich as the source type, it throws a lossy cast error. Assigning a fractional number to an integer vector is a typical example of a lossy cast error:
```{r, error = TRUE}
int_vector <- 1:3
vec_assign(int_vector, 2, 0.001)
```
# How to make two vector classes compatible?
If you encounter two vector types that you think should be compatible, they might need to implement coercion methods. Reach out to the author(s) of the classes and ask them if it makes sense for their classes to be compatible.
These developer FAQ items provide guides for implementing coercion methods:
- For an example of implementing coercion methods for simple vectors, see [`?howto-faq-coercion`][howto-faq-coercion].
- For an example of implementing coercion methods for data frame subclasses, see [`?howto-faq-coercion-data-frame`][howto-faq-coercion-data-frame].
|
/scratch/gouwar.j/cran-all/cranData/vctrs/man/faq/user/faq-compatibility-types.Rmd
|
```{r, child = "../setup.Rmd", include = FALSE}
```
This error occurs when a function expects a vector and gets a scalar object instead. This commonly happens when some code attempts to assign a scalar object as column in a data frame:
```{r, error = TRUE}
fn <- function() NULL
tibble::tibble(x = fn)
fit <- lm(1:3 ~ 1)
tibble::tibble(x = fit)
```
# Vectorness in base R and in the tidyverse
In base R, almost everything is a vector or behaves like a vector. In the tidyverse we have chosen to be a bit stricter about what is considered a vector. The main question we ask ourselves to decide on the vectorness of a type is whether it makes sense to include that object as a column in a data frame.
The main difference is that S3 lists are considered vectors by base R but in the tidyverse that's not the case by default:
```{r, error = TRUE}
fit <- lm(1:3 ~ 1)
typeof(fit)
class(fit)
# S3 lists can be subset like a vector using base R:
fit[c(1, 4)]
# But not in vctrs
vctrs::vec_slice(fit, c(1, 4))
```
Defused function calls are another (more esoteric) example:
```{r, error = TRUE}
call <- quote(foo(bar = TRUE, baz = FALSE))
call
# They can be subset like a vector using base R:
call[1:2]
lapply(call, function(x) x)
# But not with vctrs:
vctrs::vec_slice(call, 1:2)
```
# I get a scalar type error but I think this is a bug
It's possible the author of the class needs to do some work to declare their class a vector. Consider reaching out to the author. We have written a [developer FAQ page][howto-faq-fix-scalar-type-error] to help them fix the issue.
|
/scratch/gouwar.j/cran-all/cranData/vctrs/man/faq/user/faq-error-scalar-type.Rmd
|
---
title: "Printing vectors nicely in tibbles"
author: "Kirill Müller, Hadley Wickham"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Printing vectors nicely in tibbles}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r, include = FALSE}
knitr::opts_chunk$set(collapse = TRUE, comment = "#>")
```
You can get basic control over how a vector is printed in a tibble by providing a `format()` method.
If you want greater control, you need to understand how printing works.
The presentation of a column in a tibble is controlled by two S3 generics:
* `vctrs::vec_ptype_abbr()` determines what goes into the column header.
* `pillar::pillar_shaft()` determines what goes into the body, or the shaft, of the column.
Technically a [*pillar*](https://en.wikipedia.org/wiki/Column#Nomenclature) is composed of a *shaft* (decorated with an *ornament*), with a *capital* above and a *base* below.
Multiple pillars form a *colonnade*, which can be stacked in multiple *tiers*.
This is the motivation behind the names in our API.
This short vignette shows the basics of column styling using a `"latlon"` vector.
The vignette imagines the code is in a package, so that you can see the roxygen2 commands you'll need to create documentation and the `NAMESPACE` file.
In this vignette, we'll attach pillar and vctrs:
```{r setup}
library(vctrs)
library(pillar)
```
You don't need to do this in a package.
Instead, you'll need to _import_ the packages by then to the `Imports:` section of your `DESCRIPTION`.
The following helper does this for you:
```{r, eval = FALSE}
usethis::use_package("vctrs")
usethis::use_package("pillar")
```
## Prerequisites
To illustrate the basic ideas we're going to create a `"latlon"` class that encodes geographic coordinates in a record.
We'll pretend that this code lives in a package called earth.
For simplicity, the values are printed as degrees and minutes only.
By using `vctrs_rcrd()`, we already get the infrastructure to make this class fully compatible with data frames for free.
See `vignette("s3-vector", package = "vctrs")` for details on the record data type.
```{r}
#' @export
latlon <- function(lat, lon) {
new_rcrd(list(lat = lat, lon = lon), class = "earth_latlon")
}
#' @export
format.earth_latlon <- function(x, ..., formatter = deg_min) {
x_valid <- which(!is.na(x))
lat <- field(x, "lat")[x_valid]
lon <- field(x, "lon")[x_valid]
ret <- rep(NA_character_, vec_size(x))
ret[x_valid] <- paste0(formatter(lat, "lat"), " ", formatter(lon, "lon"))
# It's important to keep NA in the vector!
ret
}
deg_min <- function(x, direction) {
pm <- if (direction == "lat") c("N", "S") else c("E", "W")
sign <- sign(x)
x <- abs(x)
deg <- trunc(x)
x <- x - deg
min <- round(x * 60)
# Ensure the columns are always the same width so they line up nicely
ret <- sprintf("%d°%.2d'%s", deg, min, ifelse(sign >= 0, pm[[1]], pm[[2]]))
format(ret, justify = "right")
}
latlon(c(32.71, 2.95), c(-117.17, 1.67))
```
## Using in a tibble
Columns of this class can be used in a tibble right away because we've made a class using the vctrs infrastructure and have provided a `format()` method:
```{r}
library(tibble)
loc <- latlon(
c(28.3411783, 32.7102978, 30.2622356, 37.7859102, 28.5, NA),
c(-81.5480348, -117.1704058, -97.7403327, -122.4131357, -81.4, NA)
)
data <- tibble(venue = "rstudio::conf", year = 2017:2022, loc = loc)
data
```
This output is ok, but we could improve it by:
1. Using a more description type abbreviation than `<erth_ltl>`.
1. Using a dash of colour to highlight the most important parts of the value.
1. Providing a narrower view when horizontal space is at a premium.
The following sections show how to enhance the rendering.
## Fixing the data type
Instead of `<erth_ltl>` we'd prefer to use `<latlon>`.
We can do that by implementing the `vec_ptype_abbr()` method, which should return a string that can be used in a column header.
For your own classes, strive for an evocative abbreviation that's under 6 characters.
```{r}
#' @export
vec_ptype_abbr.earth_latlon <- function(x) {
"latlon"
}
data
```
## Custom rendering
The `format()` method is used by default for rendering.
For custom formatting you need to implement the `pillar_shaft()` method.
This function should always return a pillar shaft object, created by `new_pillar_shaft_simple()` or similar.
`new_pillar_shaft_simple()` accepts ANSI escape codes for colouring, and pillar includes some built in styles like `style_subtle()`.
We can use subtle style for the degree and minute separators to make the data more obvious.
First we define a degree formatter that makes use of `style_subtle()`:
```{r}
deg_min_color <- function(x, direction) {
pm <- if (direction == "lat") c("N", "S") else c("E", "W")
sign <- sign(x)
x <- abs(x)
deg <- trunc(x)
x <- x - deg
rad <- round(x * 60)
ret <- sprintf(
"%d%s%.2d%s%s",
deg,
pillar::style_subtle("°"),
rad,
pillar::style_subtle("'"),
pm[ifelse(sign >= 0, 1, 2)]
)
format(ret, justify = "right")
}
```
And then we pass that to our `format()` method:
```{r}
#' @importFrom pillar pillar_shaft
#' @export
pillar_shaft.earth_latlon <- function(x, ...) {
out <- format(x, formatter = deg_min_color)
pillar::new_pillar_shaft_simple(out, align = "right")
}
```
Currently, ANSI escapes are not rendered in vignettes, so this result doesn't look any different, but if you run the code yourself you'll see an improved display.
```{r}
data
```
As well as the functions in pillar, the [cli](https://cli.r-lib.org/) package provides a variety of tools for styling text.
## Truncation
Tibbles can automatically compacts columns when there's no enough horizontal space to display everything:
```{r}
print(data, width = 30)
```
Currently the latlon class isn't ever compacted because we haven't specified a minimum width when constructing the shaft.
Let's fix that and re-print the data:
```{r}
#' @importFrom pillar pillar_shaft
#' @export
pillar_shaft.earth_latlon <- function(x, ...) {
out <- format(x)
pillar::new_pillar_shaft_simple(out, align = "right", min_width = 10)
}
print(data, width = 30)
```
## Adaptive rendering
Truncation may be useful for character data, but for lat-lon data it'd be nicer to show full degrees and remove the minutes.
We'll first write a function that does this:
```{r}
deg <- function(x, direction) {
pm <- if (direction == "lat") c("N", "S") else c("E", "W")
sign <- sign(x)
x <- abs(x)
deg <- round(x)
ret <- sprintf("%d°%s", deg, pm[ifelse(sign >= 0, 1, 2)])
format(ret, justify = "right")
}
```
Then use it as part of more sophisticated implementation of the `pillar_shaft()` method:
```{r}
#' @importFrom pillar pillar_shaft
#' @export
pillar_shaft.earth_latlon <- function(x, ...) {
deg <- format(x, formatter = deg)
deg_min <- format(x)
pillar::new_pillar_shaft(
list(deg = deg, deg_min = deg_min),
width = pillar::get_max_extent(deg_min),
min_width = pillar::get_max_extent(deg),
class = "pillar_shaft_latlon"
)
}
```
Now the `pillar_shaft()` method returns an object of class `"pillar_shaft_latlon"` created by `new_pillar_shaft()`.
This object contains the necessary information to render the values, and also minimum and maximum width values.
For simplicity, both formats are pre-rendered, and the minimum and maximum widths are computed from there.
(`get_max_extent()` is a helper that computes the maximum display width occupied by the values in a character vector.)
All that's left to do is to implement a `format()` method for our new `"pillar_shaft_latlon"` class.
This method will be called with a `width` argument, which then determines which of the formats to choose.
The formatting of our choice is passed to the `new_ornament()` function:
```{r}
#' @export
format.pillar_shaft_latlon <- function(x, width, ...) {
if (get_max_extent(x$deg_min) <= width) {
ornament <- x$deg_min
} else {
ornament <- x$deg
}
pillar::new_ornament(ornament, align = "right")
}
data
print(data, width = 30)
```
## Testing
If you want to test the output of your code, you can compare it with a known state recorded in a text file. The `testthat::expect_snapshot()` function offers an easy way to test output-generating functions. It takes care about details such as Unicode, ANSI escapes, and output width. Furthermore it won't make the tests fail on CRAN. This is important because your output may rely on details out of your control, which should be fixed eventually but should not lead to your package being removed from CRAN.
Use this testthat expectation in one of your test files to create a snapshot test:
```{r eval = FALSE}
expect_snapshot(pillar_shaft(data$loc))
```
See <https://testthat.r-lib.org/articles/snapshotting.html> for more information.
|
/scratch/gouwar.j/cran-all/cranData/vctrs/vignettes/pillar.Rmd
|
---
title: "S3 vectors"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{S3 vectors}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
set.seed(1014)
```
This vignette shows you how to create your own S3 vector classes.
It focuses on the aspects of making a vector class that every class needs to worry about; you'll also need to provide methods that actually make the vector useful.
I assume that you're already familiar with the basic machinery of S3, and the vocabulary I use in Advanced R: constructor, helper, and validator.
If not, I recommend reading at least the first two sections of [the S3 chapter](https://adv-r.hadley.nz/s3.html) of *Advanced R*.
This article refers to "vectors of numbers" as *double vectors*.
Here, "double" stands for ["double precision floating point number"](https://en.wikipedia.org/wiki/Double-precision_floating-point_format), see also `double()`.
```{r setup}
library(vctrs)
library(rlang)
library(zeallot)
```
This vignette works through five big topics:
- The basics of creating a new vector class with vctrs.
- The coercion and casting system.
- The record and list-of types.
- Equality and comparison proxies.
- Arithmetic operators.
They're collectively demonstrated with a number of simple S3 classes:
- Percent: a double vector that prints as a percentage.
This illustrates the basic mechanics of class creation, coercion, and casting.
- Decimal: a double vector that always prints with a fixed number of decimal places.
This class has an attribute which needs a little extra care in casts and coercions.
- Cached sum: a double vector that caches the total sum in an attribute.
The attribute depends on the data, so needs extra care.
- Rational: a pair of integer vectors that defines a rational number like `2 / 3`.
This introduces you to the record style, and to the equality and comparison operators.
It also needs special handling for `+`, `-`, and friends.
- Polynomial: a list of integer vectors that define polynomials like `1 + x - x^3`.
Sorting such vectors correctly requires a custom equality method.
- Meter: a numeric vector with meter units.
This is the simplest possible class with interesting algebraic properties.
- Period and frequency: a pair of classes represent a period, or its inverse, frequency.
This allows us to explore more arithmetic operators.
## Basics
In this section you'll learn how to create a new vctrs class by calling `new_vctr()`.
This creates an object with class `vctrs_vctr` which has a number of methods.
These are designed to make your life as easy as possible.
For example:
- The `print()` and `str()` methods are defined in terms of `format()` so you get a pleasant, consistent display as soon as you've made your `format()` method.
- You can immediately put your new vector class in a data frame because `as.data.frame.vctrs_vctr()` does the right thing.
- Subsetting (`[`, `[[`, and `$`), `length<-`, and `rep()` methods automatically preserve attributes because they use `vec_restore()`.
A default `vec_restore()` works for all classes where the attributes are data-independent, and can easily be customised when the attributes do depend on the data.
- Default subset-assignment methods (`[<-`, `[[<-`, and `$<-`) follow the principle that the new values should be coerced to match the existing vector.
This gives predictable behaviour and clear error messages.
### Percent class
In this section, I'll show you how to make a `percent` class, i.e., a double vector that is printed as a percentage.
We start by defining a low-level [constructor](https://adv-r.hadley.nz/s3.html#s3-constrcutor) to check types and/or sizes and call `new_vctr()`.
`percent` is built on a double vector of any length and doesn't have any attributes.
```{r}
new_percent <- function(x = double()) {
if (!is_double(x)) {
abort("`x` must be a double vector.")
}
new_vctr(x, class = "vctrs_percent")
}
x <- new_percent(c(seq(0, 1, length.out = 4), NA))
x
str(x)
```
Note that we prefix the name of the class with the name of the package.
This prevents conflicting definitions between packages.
For packages that implement only one class (such as [blob](https://blob.tidyverse.org/)), it's fine to use the package name without prefix as the class name.
We then follow up with a user friendly [helper](https://adv-r.hadley.nz/s3.html#helpers).
Here we'll use `vec_cast()` to allow it to accept anything coercible to a double:
```{r}
percent <- function(x = double()) {
x <- vec_cast(x, double())
new_percent(x)
}
```
Before you go on, check that user-friendly constructor returns a zero-length vector when called with no arguments.
This makes it easy to use as a prototype.
```{r}
new_percent()
percent()
```
For the convenience of your users, consider implementing an `is_percent()` function:
```{r}
is_percent <- function(x) {
inherits(x, "vctrs_percent")
}
```
### `format()` method
The first method for every class should almost always be a `format()` method.
This should return a character vector the same length as `x`.
The easiest way to do this is to rely on one of R's low-level formatting functions like `formatC()`:
```{r}
format.vctrs_percent <- function(x, ...) {
out <- formatC(signif(vec_data(x) * 100, 3))
out[is.na(x)] <- NA
out[!is.na(x)] <- paste0(out[!is.na(x)], "%")
out
}
```
```{r, include = FALSE}
# As of R 3.5, print.vctr can not find format.percent since it's not in
# its lexical environment. We fix that problem by manually registering.
s3_register("base::format", "vctrs_percent")
```
```{r}
x
```
(Note the use of `vec_data()` so `format()` doesn't get stuck in an infinite loop, and that I take a little care to not convert `NA` to `"NA"`; this leads to better printing.)
The format method is also used by data frames, tibbles, and `str()`:
```{r}
data.frame(x)
```
For optimal display, I recommend also defining an abbreviated type name, which should be 4-5 letters for commonly used vectors.
This is used in tibbles and in `str()`:
```{r}
vec_ptype_abbr.vctrs_percent <- function(x, ...) {
"prcnt"
}
tibble::tibble(x)
str(x)
```
If you need more control over printing in tibbles, implement a method for `pillar::pillar_shaft()`.
See `vignette("pillar", package = "vctrs")` for details.
## Casting and coercion
The next set of methods you are likely to need are those related to coercion and casting.
Coercion and casting are two sides of the same coin: changing the prototype of an existing object.
When the change happens *implicitly* (e.g in `c()`) we call it **coercion**; when the change happens *explicitly* (e.g. with `as.integer(x)`), we call it **casting**.
One of the main goals of vctrs is to put coercion and casting on a robust theoretical footing so it's possible to make accurate predictions about what (e.g.) `c(x, y)` should do when `x` and `y` have different prototypes.
vctrs achieves this goal through two generics:
- `vec_ptype2(x, y)` defines possible set of coercions.
It returns a prototype if `x` and `y` can be safely coerced to the same prototype; otherwise it returns an error.
The set of automatic coercions is usually quite small because too many tend to make code harder to reason about and silently propagate mistakes.
- `vec_cast(x, to)` defines the possible sets of casts.
It returns `x` translated to have prototype `to`, or throws an error if the conversion isn't possible.
The set of possible casts is a superset of possible coercions because they're requested explicitly.
### Double dispatch
Both generics use [**double dispatch**](https://en.wikipedia.org/wiki/Double_dispatch) which means that the implementation is selected based on the class of two arguments, not just one.
S3 does not natively support double dispatch, so we implement our own dispatch mechanism.
In practice, this means:
- You end up with method names with two classes, like `vec_ptype2.foo.bar()`.
- You don't need to implement default methods (they would never be called if you do).
- You can't call `NextMethod()`.
### Percent class {#percent}
We'll make our percent class coercible back and forth with double vectors.
`vec_ptype2()` provides a user friendly error message if the coercion doesn't exist and makes sure `NA` is handled in a standard way.
`NA` is technically a logical vector, but we want to stand in for a missing value of any type.
```{r, error = TRUE}
vec_ptype2("bogus", percent())
vec_ptype2(percent(), NA)
vec_ptype2(NA, percent())
```
By default and in simple cases, an object of the same class is compatible with itself:
```{r}
vec_ptype2(percent(), percent())
```
However this only works if the attributes for both objects are the same.
Also the default methods are a bit slower.
It is always a good idea to provide an explicit coercion method for the case of identical classes.
So we'll start by saying that a `vctrs_percent` combined with a `vctrs_percent` yields a `vctrs_percent`, which we indicate by returning a prototype generated by the constructor.
```{r}
vec_ptype2.vctrs_percent.vctrs_percent <- function(x, y, ...) new_percent()
```
Next we define methods that say that combining a `percent` and double should yield a `double`.
We avoid returning a `percent` here because errors in the scale (1 vs. 0.01) are more obvious with raw numbers.
Because double dispatch is a bit of a hack, we need to provide two methods.
It's your responsibility to ensure that each member of the pair returns the same result: if they don't you will get weird and unpredictable behaviour.
The double dispatch mechanism requires us to refer to the underlying type, `double`, in the method name.
If we implemented `vec_ptype2.vctrs_percent.numeric()`, it would never be called.
```{r}
vec_ptype2.vctrs_percent.double <- function(x, y, ...) double()
vec_ptype2.double.vctrs_percent <- function(x, y, ...) double()
```
We can check that we've implemented this correctly with `vec_ptype_show()`:
```{r}
vec_ptype_show(percent(), double(), percent())
```
The `vec_ptype2()` methods define which input is the richer type that vctrs should coerce to.
However, they don't perform any conversion.
This is the job of `vec_cast()`, which we implement next.
We'll provide a method to cast a percent to a percent:
```{r}
vec_cast.vctrs_percent.vctrs_percent <- function(x, to, ...) x
```
And then for converting back and forth between doubles.
To convert a double to a percent we use the `percent()` helper (not the constructor; this is unvalidated user input).
To convert a `percent` to a double, we strip the attributes.
Note that for historical reasons the order of argument in the signature is the opposite as for `vec_ptype2()`.
The class for `to` comes first, and the class for `x` comes second.
Again, the double dispatch mechanism requires us to refer to the underlying type, `double`, in the method name.
Implementing `vec_cast.vctrs_percent.numeric()` has no effect.
```{r}
vec_cast.vctrs_percent.double <- function(x, to, ...) percent(x)
vec_cast.double.vctrs_percent <- function(x, to, ...) vec_data(x)
```
Then we can check this works with `vec_cast()`:
```{r}
vec_cast(0.5, percent())
vec_cast(percent(0.5), double())
```
Once you've implemented `vec_ptype2()` and `vec_cast()`, you get `vec_c()`, `[<-`, and `[[<-` implementations for free.
```{r, error = TRUE}
vec_c(percent(0.5), 1)
vec_c(NA, percent(0.5))
# but
vec_c(TRUE, percent(0.5))
x <- percent(c(0.5, 1, 2))
x[1:2] <- 2:1
x[[3]] <- 0.5
x
```
You'll also get mostly correct behaviour for `c()`.
The exception is when you use `c()` with a base R class:
```{r, error = TRUE}
# Correct
c(percent(0.5), 1)
c(percent(0.5), factor(1))
# Incorrect
c(factor(1), percent(0.5))
```
Unfortunately there's no way to fix this problem with the current design of `c()`.
Again, as a convenience, consider providing an `as_percent()` function that makes use of the casts defined in your `vec_cast.vctrs_percent()` methods:
```{r}
as_percent <- function(x) {
vec_cast(x, new_percent())
}
```
Occasionally, it is useful to provide conversions that go beyond what's allowed in casting.
For example, we could offer a parsing method for character vectors.
In this case, `as_percent()` should be generic, the default method should cast, and then additional methods should implement more flexible conversion:
```{r}
as_percent <- function(x, ...) {
UseMethod("as_percent")
}
as_percent.default <- function(x, ...) {
vec_cast(x, new_percent())
}
as_percent.character <- function(x) {
value <- as.numeric(gsub(" *% *$", "", x)) / 100
new_percent(value)
}
```
### Decimal class
Now that you've seen the basics with a very simple S3 class, we'll gradually explore more complicated scenarios.
This section creates a `decimal` class that prints with the specified number of decimal places.
This is very similar to `percent` but now the class needs an attribute: the number of decimal places to display (an integer vector of length 1).
We start off as before, defining a low-level constructor, a user-friendly constructor, a `format()` method, and a `vec_ptype_abbr()`.
Note that additional object attributes are simply passed along to `new_vctr()`:
```{r}
new_decimal <- function(x = double(), digits = 2L) {
if (!is_double(x)) {
abort("`x` must be a double vector.")
}
if (!is_integer(digits)) {
abort("`digits` must be an integer vector.")
}
vec_check_size(digits, size = 1L)
new_vctr(x, digits = digits, class = "vctrs_decimal")
}
decimal <- function(x = double(), digits = 2L) {
x <- vec_cast(x, double())
digits <- vec_recycle(vec_cast(digits, integer()), 1L)
new_decimal(x, digits = digits)
}
digits <- function(x) attr(x, "digits")
format.vctrs_decimal <- function(x, ...) {
sprintf(paste0("%-0.", digits(x), "f"), x)
}
vec_ptype_abbr.vctrs_decimal <- function(x, ...) {
"dec"
}
x <- decimal(runif(10), 1L)
x
```
Note that I provide a little helper to extract the `digits` attribute.
This makes the code a little easier to read and should not be exported.
By default, vctrs assumes that attributes are independent of the data and so are automatically preserved.
You'll see what to do if the attributes are data dependent in the next section.
```{r}
x[1:2]
x[[1]]
```
For the sake of exposition, we'll assume that `digits` is an important attribute of the class and should be included in the full type:
```{r}
vec_ptype_full.vctrs_decimal <- function(x, ...) {
paste0("decimal<", digits(x), ">")
}
x
```
Now consider `vec_cast()` and `vec_ptype2()`.
Casting and coercing from one decimal to another requires a little thought as the values of the `digits` attribute might be different, and we need some way to reconcile them.
Here I've decided to chose the maximum of the two; other reasonable options are to take the value from the left-hand side or throw an error.
```{r}
vec_ptype2.vctrs_decimal.vctrs_decimal <- function(x, y, ...) {
new_decimal(digits = max(digits(x), digits(y)))
}
vec_cast.vctrs_decimal.vctrs_decimal <- function(x, to, ...) {
new_decimal(vec_data(x), digits = digits(to))
}
vec_c(decimal(1/100, digits = 3), decimal(2/100, digits = 2))
```
Finally, I can implement coercion to and from other types, like doubles.
When automatically coercing, I choose the richer type (i.e., the decimal).
```{r}
vec_ptype2.vctrs_decimal.double <- function(x, y, ...) x
vec_ptype2.double.vctrs_decimal <- function(x, y, ...) y
vec_cast.vctrs_decimal.double <- function(x, to, ...) new_decimal(x, digits = digits(to))
vec_cast.double.vctrs_decimal <- function(x, to, ...) vec_data(x)
vec_c(decimal(1, digits = 1), pi)
vec_c(pi, decimal(1, digits = 1))
```
If type `x` has greater resolution than `y`, there will be some inputs that lose precision.
These should generate errors using `stop_lossy_cast()`.
You can see that in action when casting from doubles to integers; only some doubles can become integers without losing resolution.
```{r, error = TRUE}
vec_cast(c(1, 2, 10), to = integer())
vec_cast(c(1.5, 2, 10.5), to = integer())
```
### Cached sum class {#cached-sum}
The next level up in complexity is an object that has data-dependent attributes.
To explore this idea we'll create a vector that caches the sum of its values.
As usual, we start with low-level and user-friendly constructors:
```{r}
new_cached_sum <- function(x = double(), sum = 0L) {
if (!is_double(x)) {
abort("`x` must be a double vector.")
}
if (!is_double(sum)) {
abort("`sum` must be a double vector.")
}
vec_check_size(sum, size = 1L)
new_vctr(x, sum = sum, class = "vctrs_cached_sum")
}
cached_sum <- function(x) {
x <- vec_cast(x, double())
new_cached_sum(x, sum(x))
}
```
For this class, we can use the default `format()` method, and instead, we'll customise the `obj_print_footer()` method.
This is a good place to display user facing attributes.
```{r}
obj_print_footer.vctrs_cached_sum <- function(x, ...) {
cat("# Sum: ", format(attr(x, "sum"), digits = 3), "\n", sep = "")
}
x <- cached_sum(runif(10))
x
```
We'll also override `sum()` and `mean()` to use the attribute.
This is easiest to do with `vec_math()`, which you'll learn about later.
```{r}
vec_math.vctrs_cached_sum <- function(.fn, .x, ...) {
cat("Using cache\n")
switch(.fn,
sum = attr(.x, "sum"),
mean = attr(.x, "sum") / length(.x),
vec_math_base(.fn, .x, ...)
)
}
sum(x)
```
As mentioned above, vctrs assumes that attributes are independent of the data.
This means that when we take advantage of the default methods, they'll work, but return the incorrect result:
```{r}
x[1:2]
```
To fix this, you need to provide a `vec_restore()` method.
Note that this method dispatches on the `to` argument.
```{r}
vec_restore.vctrs_cached_sum <- function(x, to, ..., i = NULL) {
new_cached_sum(x, sum(x))
}
x[1]
```
This works because most of the vctrs methods dispatch to the underlying base function by first stripping off extra attributes with `vec_data()` and then reapplying them again with `vec_restore()`.
The default `vec_restore()` method copies over all attributes, which is not appropriate when the attributes depend on the data.
Note that `vec_restore.class` is subtly different from `vec_cast.class.class()`.
`vec_restore()` is used when restoring attributes that have been lost; `vec_cast()` is used for coercions.
This is easier to understand with a concrete example.
Imagine factors were implemented with `new_vctr()`.
`vec_restore.factor()` would restore attributes back to an integer vector, but you would not want to allow manually casting an integer to a factor with `vec_cast()`.
## Record-style objects
Record-style objects use a list of equal-length vectors to represent individual components of the object.
The best example of this is `POSIXlt`, which underneath the hood is a list of 11 fields like year, month, and day.
Record-style classes override `length()` and subsetting methods to conceal this implementation detail.
```{r}
x <- as.POSIXlt(ISOdatetime(2020, 1, 1, 0, 0, 1:3))
x
length(x)
length(unclass(x))
x[[1]] # the first date time
unclass(x)[[1]] # the first component, the number of seconds
```
vctrs makes it easy to create new record-style classes using `new_rcrd()`, which has a wide selection of default methods.
### Rational class
A fraction, or rational number, can be represented by a pair of integer vectors representing the numerator (the number on top) and the denominator (the number on bottom), where the length of each vector must be the same.
To represent such a data structure we turn to a new base data type: the record (or rcrd for short).
As usual we start with low-level and user-friendly constructors.
The low-level constructor calls `new_rcrd()`, which needs a named list of equal-length vectors.
```{r}
new_rational <- function(n = integer(), d = integer()) {
if (!is_integer(n)) {
abort("`n` must be an integer vector.")
}
if (!is_integer(d)) {
abort("`d` must be an integer vector.")
}
new_rcrd(list(n = n, d = d), class = "vctrs_rational")
}
```
Our user friendly constructor casts `n` and `d` to integers and recycles them to the same length.
```{r}
rational <- function(n = integer(), d = integer()) {
c(n, d) %<-% vec_cast_common(n, d, .to = integer())
c(n, d) %<-% vec_recycle_common(n, d)
new_rational(n, d)
}
x <- rational(1, 1:10)
```
Behind the scenes, `x` is a named list with two elements.
But those details are hidden so that it behaves like a vector:
```{r}
names(x)
length(x)
```
To access the underlying fields we need to use `field()` and `fields()`:
```{r}
fields(x)
field(x, "n")
```
Notice that we can't `print()` or `str()` the new rational vector `x` yet.
Printing causes an error:
```{r, error = TRUE}
x
str(x)
```
This is because we haven't defined how our class can be printed from the underlying data.
Note that if you want to look under the hood during development, you can always call `vec_data(x)`.
```{r}
vec_data(x)
str(vec_data(x))
```
It is generally best to define a formatting method early in the development of a class.
The format method defines how to display the class so that it can be printed in the normal way:
```{r}
format.vctrs_rational <- function(x, ...) {
n <- field(x, "n")
d <- field(x, "d")
out <- paste0(n, "/", d)
out[is.na(n) | is.na(d)] <- NA
out
}
vec_ptype_abbr.vctrs_rational <- function(x, ...) "rtnl"
vec_ptype_full.vctrs_rational <- function(x, ...) "rational"
x
```
vctrs uses the `format()` method in `str()`, hiding the underlying implementation details from the user:
```{r}
str(x)
```
For `rational`, `vec_ptype2()` and `vec_cast()` follow the same pattern as `percent()`.
We allow coercion from integer and to doubles.
```{r}
vec_ptype2.vctrs_rational.vctrs_rational <- function(x, y, ...) new_rational()
vec_ptype2.vctrs_rational.integer <- function(x, y, ...) new_rational()
vec_ptype2.integer.vctrs_rational <- function(x, y, ...) new_rational()
vec_cast.vctrs_rational.vctrs_rational <- function(x, to, ...) x
vec_cast.double.vctrs_rational <- function(x, to, ...) field(x, "n") / field(x, "d")
vec_cast.vctrs_rational.integer <- function(x, to, ...) rational(x, 1)
vec_c(rational(1, 2), 1L, NA)
```
### Decimal2 class
The previous implementation of `decimal` was built on top of doubles.
This is a bad idea because decimal vectors are typically used when you care about precise values (i.e., dollars and cents in a bank account), and double values suffer from floating point problems.
A better implementation of a decimal class would be to use pair of integers, one for the value to the left of the decimal point, and the other for the value to the right (divided by a `scale`).
The following code is a very quick sketch of how you might start creating such a class:
```{r}
new_decimal2 <- function(l, r, scale = 2L) {
if (!is_integer(l)) {
abort("`l` must be an integer vector.")
}
if (!is_integer(r)) {
abort("`r` must be an integer vector.")
}
if (!is_integer(scale)) {
abort("`scale` must be an integer vector.")
}
vec_check_size(scale, size = 1L)
new_rcrd(list(l = l, r = r), scale = scale, class = "vctrs_decimal2")
}
decimal2 <- function(l, r, scale = 2L) {
l <- vec_cast(l, integer())
r <- vec_cast(r, integer())
c(l, r) %<-% vec_recycle_common(l, r)
scale <- vec_cast(scale, integer())
# should check that r < 10^scale
new_decimal2(l = l, r = r, scale = scale)
}
format.vctrs_decimal2 <- function(x, ...) {
val <- field(x, "l") + field(x, "r") / 10^attr(x, "scale")
sprintf(paste0("%.0", attr(x, "scale"), "f"), val)
}
decimal2(10, c(0, 5, 99))
```
## Equality and comparison
vctrs provides four "proxy" generics.
Two of these let you control how your class determines equality and comparison:
- `vec_proxy_equal()` returns a data vector suitable for comparison.
It underpins `==`, `!=`, `unique()`, `anyDuplicated()`, and `is.na()`.
- `vec_proxy_compare()` specifies how to compare the elements of your vector.
This proxy is used in `<`, `<=`, `>=`, `>`, `min()`, `max()`, `median()`, and `quantile()`.
Two other proxy generic are used for sorting for unordered data types and for accessing the raw data for exotic storage formats:
- `vec_proxy_order()` specifies how to sort the elements of your vector.
It is used in `xtfrm()`, which in turn is called by the `order()` and `sort()` functions.
This proxy was added to implement the behaviour of lists, which are sortable (their order proxy sorts by first occurrence) but not comparable (comparison operators cause an error).
Its default implementation for other classes calls `vec_proxy_compare()` and you normally don't need to implement this proxy.
- `vec_proxy()` returns the actual data of a vector.
This is useful when you store the data in a field of your class.
Most of the time, you shouldn't need to implement `vec_proxy()`.
The default behavior is as follows:
- `vec_proxy_equal()` calls `vec_proxy()`
- `vec_proxy_compare()` calls `vec_proxy_equal()`
- `vec_proxy_order()` calls `vec_proxy_compare()`
You should only implement these proxies when some preprocessing on the data is needed to make elements comparable.
In that case, defining these methods will get you a lot of behaviour for relatively little work.
These proxy functions should always return a simple object (either a bare vector or a data frame) that possesses the same properties as your class.
This permits efficient implementation of the vctrs internals because it allows dispatch to happen once in R, and then efficient computations can be written in C.
### Rational class
Let's explore these ideas by with the rational class we started on above.
By default, `vec_proxy()` converts a record to a data frame, and the default comparison works column by column:
```{r}
x <- rational(c(1, 2, 1, 2), c(1, 1, 2, 2))
x
vec_proxy(x)
x == rational(1, 1)
```
This makes sense as a default but isn't correct here because `rational(1, 1)` represents the same number as `rational(2, 2)`, so they should be equal.
We can fix that by implementing a `vec_proxy_equal()` method that divides `n` and `d` by their greatest common divisor:
```{r}
# Thanks to Matthew Lundberg: https://stackoverflow.com/a/21504113/16632
gcd <- function(x, y) {
r <- x %% y
ifelse(r, gcd(y, r), y)
}
vec_proxy_equal.vctrs_rational <- function(x, ...) {
n <- field(x, "n")
d <- field(x, "d")
gcd <- gcd(n, d)
data.frame(n = n / gcd, d = d / gcd)
}
vec_proxy_equal(x)
x == rational(1, 1)
```
`vec_proxy_equal()` is also used by `unique()`:
```{r}
unique(x)
```
We now need to fix the comparison operations similarly, since comparison currently happens lexicographically by `n`, then by `d`:
```{r}
rational(1, 2) < rational(2, 3)
rational(2, 4) < rational(2, 3)
```
The easiest fix is to convert the fraction to a floating point number and use this as a proxy:
```{r}
vec_proxy_compare.vctrs_rational <- function(x, ...) {
field(x, "n") / field(x, "d")
}
rational(2, 4) < rational(2, 3)
```
This also fixes `sort()`, because the default implementation of `vec_proxy_order()` calls `vec_proxy_compare()`.
```{r}
sort(x)
```
(We could have used the same approach in `vec_proxy_equal()`, but when working with floating point numbers it's not necessarily true that `x == y` implies that `d * x == d * y`.)
### Polynomial class
A related problem occurs if we build our vector on top of a list.
The following code defines a polynomial class that represents polynomials (like `1 + 3x - 2x^2`) using a list of integer vectors (like `c(1, 3, -2)`).
Note the use of `new_list_of()` in the constructor.
```{r}
poly <- function(...) {
x <- vec_cast_common(..., .to = integer())
new_poly(x)
}
new_poly <- function(x) {
new_list_of(x, ptype = integer(), class = "vctrs_poly_list")
}
vec_ptype_full.vctrs_poly_list <- function(x, ...) "polynomial"
vec_ptype_abbr.vctrs_poly_list <- function(x, ...) "poly"
format.vctrs_poly_list <- function(x, ...) {
format_one <- function(x) {
if (length(x) == 0) {
return("")
}
if (length(x) == 1) {
format(x)
} else {
suffix <- c(paste0("\u22C5x^", seq(length(x) - 1, 1)), "")
out <- paste0(x, suffix)
out <- out[x != 0L]
paste0(out, collapse = " + ")
}
}
vapply(x, format_one, character(1))
}
obj_print_data.vctrs_poly_list <- function(x, ...) {
if (length(x) != 0) {
print(format(x), quote = FALSE)
}
}
p <- poly(1, c(1, 0, 0, 0, 2), c(1, 0, 1))
p
```
The resulting objects will inherit from the `vctrs_list_of` class, which provides tailored methods for `$`, `[[`, the corresponding assignment operators, and other methods.
```{r}
class(p)
p[2]
p[[2]]
```
The class implements the list interface:
```{r}
obj_is_list(p)
```
This is fine for the internal implementation of this class but it would be more appropriate if it behaved like an atomic vector rather than a list.
#### Make an atomic polynomial vector
An atomic vector is a vector like integer or character for which `[[` returns the same type.
Unlike lists, you can't reach inside an atomic vector.
To make the polynomial class an atomic vector, we'll wrap the internal `list_of()` class within a record vector.
Usually records are used because they can store several fields of data for each observation.
Here we have only one, but we use the class anyway to inherit its atomicity.
```{r}
poly <- function(...) {
x <- vec_cast_common(..., .to = integer())
x <- new_poly(x)
new_rcrd(list(data = x), class = "vctrs_poly")
}
format.vctrs_poly <- function(x, ...) {
format(field(x, "data"))
}
```
The new `format()` method delegates to the one we wrote for the internal list.
The vector looks just like before:
```{r}
p <- poly(1, c(1, 0, 0, 0, 2), c(1, 0, 1))
p
```
Making the class atomic means that `obj_is_list()` now returns `FALSE`.
This prevents recursive algorithms that traverse lists from reaching too far inside the polynomial internals.
```{r}
obj_is_list(p)
```
Most importantly, it prevents users from reaching into the internals with `[[`:
```{r}
p[[2]]
```
#### Implementing equality and comparison
Equality works out of the box because we can tell if two integer vectors are equal:
```{r}
p == poly(c(1, 0, 1))
```
We can't compare individual elements, because the data is stored in a list and by default lists are not comparable:
```{r, error = TRUE}
p < p[2]
```
To enable comparison, we implement a `vec_proxy_compare()` method:
```{r}
vec_proxy_compare.vctrs_poly <- function(x, ...) {
# Get the list inside the record vector
x_raw <- vec_data(field(x, "data"))
# First figure out the maximum length
n <- max(vapply(x_raw, length, integer(1)))
# Then expand all vectors to this length by filling in with zeros
full <- lapply(x_raw, function(x) c(rep(0L, n - length(x)), x))
# Then turn into a data frame
as.data.frame(do.call(rbind, full))
}
p < p[2]
```
Often, this is sufficient to also implement `sort()`.
However, for lists, there is already a default `vec_proxy_order()` method that sorts by first occurrence:
```{r}
sort(p)
sort(p[c(1:3, 1:2)])
```
To ensure consistency between ordering and comparison, we forward `vec_proxy_order()` to `vec_proxy_compare()`:
```{r}
vec_proxy_order.vctrs_poly <- function(x, ...) {
vec_proxy_compare(x, ...)
}
sort(p)
```
## Arithmetic
vctrs also provides two mathematical generics that allow you to define a broad swath of mathematical behaviour at once:
- `vec_math(fn, x, ...)` specifies the behaviour of mathematical functions like `abs()`, `sum()`, and `mean()`.
(Note that `var()` and `sd()` can't be overridden, see `?vec_math()` for the complete list supported by `vec_math()`.)
- `vec_arith(op, x, y)` specifies the behaviour of the arithmetic operations like `+`, `-`, and `%%`.
(See `?vec_arith()` for the complete list.)
Both generics define the behaviour for multiple functions because `sum.vctrs_vctr(x)` calls `vec_math.vctrs_vctr("sum", x)`, and `x + y` calls `vec_math.x_class.y_class("+", x, y)`.
They're accompanied by `vec_math_base()` and `vec_arith_base()` which make it easy to call the underlying base R functions.
`vec_arith()` uses double dispatch and needs the following standard boilerplate:
```{r}
vec_arith.MYCLASS <- function(op, x, y, ...) {
UseMethod("vec_arith.MYCLASS", y)
}
vec_arith.MYCLASS.default <- function(op, x, y, ...) {
stop_incompatible_op(op, x, y)
}
```
Correctly exporting `vec_arith()` methods from a package is currently a little awkward.
See the instructions in the Arithmetic section of the "Implementing a vctrs S3 class in a package" section below.
### Cached sum class
I showed an example of `vec_math()` to define `sum()` and `mean()` methods for `cached_sum`.
Now let's talk about exactly how it works.
Most `vec_math()` functions will have a similar form.
You use a switch statement to handle the methods that you care about and fall back to `vec_math_base()` for those that you don't care about.
```{r}
vec_math.vctrs_cached_sum <- function(.fn, .x, ...) {
switch(.fn,
sum = attr(.x, "sum"),
mean = attr(.x, "sum") / length(.x),
vec_math_base(.fn, .x, ...)
)
}
```
### Meter class
To explore the infix arithmetic operators exposed by `vec_arith()` I'll create a new class that represents a measurement in `meter`s:
```{r}
new_meter <- function(x) {
stopifnot(is.double(x))
new_vctr(x, class = "vctrs_meter")
}
format.vctrs_meter <- function(x, ...) {
paste0(format(vec_data(x)), " m")
}
meter <- function(x) {
x <- vec_cast(x, double())
new_meter(x)
}
x <- meter(1:10)
x
```
Because `meter` is built on top of a double vector, basic mathematic operations work:
```{r}
sum(x)
mean(x)
```
But we can't do arithmetic:
```{r, error = TRUE}
x + 1
meter(10) + meter(1)
meter(10) * 3
```
To allow these infix functions to work, we'll need to provide `vec_arith()` generic.
But before we do that, let's think about what combinations of inputs we should support:
- It makes sense to add and subtract meters: that yields another meter.
We can divide a meter by another meter (yielding a unitless number), but we can't multiply meters (because that would yield an area).
- For a combination of meter and number multiplication and division by a number are acceptable.
Addition and subtraction don't make much sense as we, strictly speaking, are dealing with objects of different nature.
`vec_arith()` is another function that uses double dispatch, so as usual we start with a template.
```{r}
vec_arith.vctrs_meter <- function(op, x, y, ...) {
UseMethod("vec_arith.vctrs_meter", y)
}
vec_arith.vctrs_meter.default <- function(op, x, y, ...) {
stop_incompatible_op(op, x, y)
}
```
Then write the method for two meter objects.
We use a switch statement to cover the cases we care about and `stop_incompatible_op()` to throw an informative error message for everything else.
```{r, error = TRUE}
vec_arith.vctrs_meter.vctrs_meter <- function(op, x, y, ...) {
switch(
op,
"+" = ,
"-" = new_meter(vec_arith_base(op, x, y)),
"/" = vec_arith_base(op, x, y),
stop_incompatible_op(op, x, y)
)
}
meter(10) + meter(1)
meter(10) - meter(1)
meter(10) / meter(1)
meter(10) * meter(1)
```
Next we write the pair of methods for arithmetic with a meter and a number.
These are almost identical, but while `meter(10) / 2` makes sense, `2 / meter(10)` does not (and neither do addition and subtraction).
To support both doubles and integers as operands, we dispatch over `numeric` here instead of `double`.
```{r, error = TRUE}
vec_arith.vctrs_meter.numeric <- function(op, x, y, ...) {
switch(
op,
"/" = ,
"*" = new_meter(vec_arith_base(op, x, y)),
stop_incompatible_op(op, x, y)
)
}
vec_arith.numeric.vctrs_meter <- function(op, x, y, ...) {
switch(
op,
"*" = new_meter(vec_arith_base(op, x, y)),
stop_incompatible_op(op, x, y)
)
}
meter(2) * 10
meter(2) * as.integer(10)
10 * meter(2)
meter(20) / 10
10 / meter(20)
meter(20) + 10
```
For completeness, we also need `vec_arith.vctrs_meter.MISSING` for the unary `+` and `-` operators:
```{r}
vec_arith.vctrs_meter.MISSING <- function(op, x, y, ...) {
switch(op,
`-` = x * -1,
`+` = x,
stop_incompatible_op(op, x, y)
)
}
-meter(1)
+meter(1)
```
## Implementing a vctrs S3 class in a package
Defining S3 methods interactively is fine for iteration and exploration, but if your class lives in a package, you need to do a few more things:
- Register the S3 methods by listing them in the `NAMESPACE` file.
- Create documentation around your methods, for the sake of your user and to satisfy `R CMD check`.
Let's assume that the `percent` class is implemented in the pizza package in the file `R/percent.R`.
Here we walk through the major sections of this hypothetical file.
You've seen all of this code before, but now it's augmented by the roxygen2 directives that produce the correct `NAMESPACE` entries and help topics.
### Getting started
First, the pizza package needs to include vctrs in the `Imports` section of its `DESCRIPTION` (perhaps by calling `usethis::use_package("vctrs")`.
While vctrs is under very active development, it probably makes sense to state a minimum version.
Imports:
a_package,
another_package,
...
vctrs (>= x.y.z),
...
Then we make all vctrs functions available within the pizza package by including the directive `#' @import vctrs` somewhere.
Usually, it's not good practice to `@import` the entire namespace of a package, but vctrs is deliberately designed with this use case in mind.
Where should we put `#' @import vctrs`?
There are two natural locations:
- With package-level docs in `R/pizza-doc.R`.
You can use `usethis::use_package_doc()` to initiate this package-level documentation.
- In `R/percent.R`. This makes the most sense when the vctrs S3 class is a modest and self-contained part of the overall package.
We also must use one of these locations to dump some internal documentation that's needed to avoid `R CMD check` complaints.
We don't expect any human to ever read this documentation.
Here's how this dummy documentation should look, combined with the `#' @import vctrs` directive described above.
```{r eval = FALSE}
#' Internal vctrs methods
#'
#' @import vctrs
#' @keywords internal
#' @name pizza-vctrs
NULL
```
This should appear in `R/pizza-doc.R` (package-level docs) or in `R/percent.R` (class-focused file).
Remember to call `devtools::document()` regularly, as you develop, to regenerate `NAMESPACE` and the `.Rd` files.
From this point on, the code shown is expected to appear in `R/percent.R`.
### Low-level and user-friendly constructors
Next we add our constructor:
```{r}
new_percent <- function(x = double()) {
if (!is_double(x)) {
abort("`x` must be a double vector.")
}
new_vctr(x, class = "pizza_percent")
}
```
Note that the name of the package must be included in the class name (`pizza_percent`), but it does not need to be included in the constructor name.
You do not need to export the constructor, unless you want people to extend your class.
We can also add a call to `setOldClass()` for compatibility with S4:
```{r}
# for compatibility with the S4 system
methods::setOldClass(c("pizza_percent", "vctrs_vctr"))
```
Because we've used a function from the methods package, you'll also need to add methods to `Imports`, with (e.g.) `usethis::use_package("methods")`.
This is a "free" dependency because methods is bundled with every R install.
Next we implement, export, and document a user-friendly helper: `percent()`.
```{r}
#' `percent` vector
#'
#' This creates a double vector that represents percentages so when it is
#' printed, it is multiplied by 100 and suffixed with `%`.
#'
#' @param x A numeric vector
#' @return An S3 vector of class `pizza_percent`.
#' @export
#' @examples
#' percent(c(0.25, 0.5, 0.75))
percent <- function(x = double()) {
x <- vec_cast(x, double())
new_percent(x)
}
```
(Again note that the package name will appear in the class, but does not need to occur in the function, because we can already do `pizza::percent()`; it would be redundant to have `pizza::pizza_percent()`.)
### Other helpers
It's a good idea to provide a function that tests if an object is of this class.
If you do so, it makes sense to document it with the user-friendly constructor `percent()`:
```{r}
#' @export
#' @rdname percent
is_percent <- function(x) {
inherits(x, "pizza_percent")
}
```
You'll also need to update the `percent()` documentation to reflect that `x` now means two different things:
```{r}
#' @param x
#' * For `percent()`: A numeric vector
#' * For `is_percent()`: An object to test.
```
Next we provide the key methods to make printing work.
These are S3 methods, so they don't need to be documented, but they do need to be exported.
```{r eval = FALSE}
#' @export
format.pizza_percent <- function(x, ...) {
out <- formatC(signif(vec_data(x) * 100, 3))
out[is.na(x)] <- NA
out[!is.na(x)] <- paste0(out[!is.na(x)], "%")
out
}
#' @export
vec_ptype_abbr.pizza_percent <- function(x, ...) {
"prcnt"
}
```
Finally, we implement methods for `vec_ptype2()` and `vec_cast()`.
```{r, eval = FALSE}
#' @export
vec_ptype2.vctrs_percent.vctrs_percent <- function(x, y, ...) new_percent()
#' @export
vec_ptype2.double.vctrs_percent <- function(x, y, ...) double()
#' @export
vec_cast.pizza_percent.pizza_percent <- function(x, to, ...) x
#' @export
vec_cast.pizza_percent.double <- function(x, to, ...) percent(x)
#' @export
vec_cast.double.pizza_percent <- function(x, to, ...) vec_data(x)
```
### Arithmetic
Writing double dispatch methods for `vec_arith()` is currently more awkward than writing them for `vec_ptype2()` or `vec_cast()`.
We plan to improve this in the future.
For now, you can use the following instructions.
If you define a new type and want to write `vec_arith()` methods for it, you'll need to provide a new single dispatch S3 generic for it of the following form:
```{r, eval=FALSE}
#' @export
#' @method vec_arith my_type
vec_arith.my_type <- function(op, x, y, ...) {
UseMethod("vec_arith.my_type", y)
}
```
Note that this actually functions as both an S3 method for `vec_arith()` and an S3 generic called `vec_arith.my_type()` that dispatches off `y`.
roxygen2 only recognizes it as an S3 generic, so you have to register the S3 method part of this with an explicit `@method` call.
After that, you can define double dispatch methods, but you still need an explicit `@method` tag to ensure it is registered with the correct generic:
```{r, eval=FALSE}
#' @export
#' @method vec_arith.my_type my_type
vec_arith.my_type.my_type <- function(op, x, y, ...) {
# implementation here
}
#' @export
#' @method vec_arith.my_type integer
vec_arith.my_type.integer <- function(op, x, y, ...) {
# implementation here
}
#' @export
#' @method vec_arith.integer my_type
vec_arith.integer.my_type <- function(op, x, y, ...) {
# implementation here
}
```
vctrs provides the hybrid S3 generics/methods for most of the base R types, like `vec_arith.integer()`.
If you don't fully import vctrs with `@import vctrs`, then you will need to explicitly import the generic you are registering double dispatch methods for with `@importFrom vctrs vec_arith.integer`.
### Testing
It's good practice to test your new class.
Specific recommendations:
- `R/percent.R` is the type of file where you really do want 100% test coverage.
You can use `devtools::test_coverage_file()` to check this.
- Make sure to test behaviour with zero-length inputs and missing values.
- Use `testthat::verify_output()` to test your format method.
Customised printing is often a primary motivation for creating your own S3 class in the first place, so this will alert you to unexpected changes in your printed output.
Read more about `verify_output()` in the [testthat v2.3.0 blog post](https://www.tidyverse.org/blog/2019/11/testthat-2-3-0/); it's an example of a so-called [golden test](https://ro-che.info/articles/2017-12-04-golden-tests).
- Check for method symmetry; use `expect_s3_class()`, probably with `exact = TRUE`, to ensure that `vec_c(x, y)` and `vec_c(y, x)` return the same type of output for the important `x`s and `y`s in your domain.
- Use `testthat::expect_error()` to check that inputs that can't be combined fail with an error.
Here, you should be generally checking the class of the error, not its message.
Relevant classes include `vctrs_error_assert_ptype`, `vctrs_error_assert_size`, and `vctrs_error_incompatible_type`.
```{r, eval = FALSE}
expect_error(vec_c(1, "a"), class = "vctrs_error_incompatible_type")
```
If your tests pass when run by `devtools::test()`, but fail when run in `R CMD check`, it is very likely to reflect a problem with S3 method registration.
Carefully check your roxygen2 comments and the generated `NAMESPACE`.
### Existing classes
Before you build your own class, you might want to consider using, or subclassing existing classes.
You can check [awesome-vctrs](https://github.com/krlmlr/awesome-vctrs) for a curated list of R vector classes, some of which are built with vctrs.
If you've built or extended a class, consider adding it to that list so other people can use it.
|
/scratch/gouwar.j/cran-all/cranData/vctrs/vignettes/s3-vector.Rmd
|
---
title: "Type and size stability"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Type and size stability}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
```
This vignette introduces the ideas of type-stability and size-stability. If a function possesses these properties, it is substantially easier to reason about because to predict the "shape" of the output you only need to know the "shape"s of the inputs.
This work is partly motivated by a common pattern that I noticed when reviewing code: if I read the code (without running it!), and I can't predict the type of each variable, I feel very uneasy about the code. This sense is important because most unit tests explore typical inputs, rather than exhaustively testing the strange and unusual. Analysing the types (and size) of variables makes it possible to spot unpleasant edge cases.
```{r setup}
library(vctrs)
library(rlang)
library(zeallot)
```
## Definitions
We say a function is __type-stable__ iff:
1. You can predict the output type knowing only the input types.
1. The order of arguments in ... does not affect the output type.
Similarly, a function is __size-stable__ iff:
1. You can predict the output size knowing only the input sizes, or
there is a single numeric input that specifies the output size.
Very few base R functions are size-stable, so I'll also define a slightly weaker condition. I'll call a function __length-stable__ iff:
1. You can predict the output _length_ knowing only the input _lengths_, or
there is a single numeric input that specifies the output _length_.
(But note that length-stable is not a particularly robust definition because `length()` returns a value for things that are not vectors.)
We'll call functions that don't obey these principles __type-unstable__ and __size-unstable__ respectively.
On top of type- and size-stability it's also desirable to have a single set of rules that are applied consistently. We want one set of type-coercion and size-recycling rules that apply everywhere, not many sets of rules that apply to different functions.
The goal of these principles is to minimise cognitive overhead. Rather than having to memorise many special cases, you should be able to learn one set of principles and apply them again and again.
### Examples
To make these ideas concrete, let's apply them to a few base functions:
1. `mean()` is trivially type-stable and size-stable because it always returns
a double vector of length 1 (or it throws an error).
1. Surprisingly, `median()` is type-unstable:
```{r}
vec_ptype_show(median(c(1L, 1L)))
vec_ptype_show(median(c(1L, 1L, 1L)))
```
It is, however, size-stable, since it always returns a vector of length 1.
1. `sapply()` is type-unstable because you can't predict the output type only
knowing the input types:
```{r}
vec_ptype_show(sapply(1L, function(x) c(x, x)))
vec_ptype_show(sapply(integer(), function(x) c(x, x)))
```
It's not quite size-stable; `vec_size(sapply(x, f))` is `vec_size(x)`
for vectors but not for matrices (the output is transposed) or
data frames (it iterates over the columns).
1. `vapply()` is a type-stable version of `sapply()` because
`vec_ptype_show(vapply(x, fn, template))` is always `vec_ptype_show(template)`.
It is size-unstable for the same reasons as `sapply()`.
1. `c()` is type-unstable because `c(x, y)` doesn't always output the same type
as `c(y, x)`.
```{r}
vec_ptype_show(c(NA, Sys.Date()))
vec_ptype_show(c(Sys.Date(), NA))
```
`c()` is *almost always* length-stable because `length(c(x, y))`
*almost always* equals `length(x) + length(y)`. One common source of
instability here is dealing with non-vectors (see the later section
"Non-vectors"):
```{r}
env <- new.env(parent = emptyenv())
length(env)
length(mean)
length(c(env, mean))
```
1. `paste(x1, x2)` is length-stable because `length(paste(x1, x2))`
equals `max(length(x1), length(x2))`. However, it doesn't follow the usual
arithmetic recycling rules because `paste(1:2, 1:3)` doesn't generate
a warning.
1. `ifelse()` is length-stable because `length(ifelse(cond, true, false))`
is always `length(cond)`. `ifelse()` is type-unstable because the output
type depends on the value of `cond`:
```{r}
vec_ptype_show(ifelse(NA, 1L, 1L))
vec_ptype_show(ifelse(FALSE, 1L, 1L))
```
1. `read.csv(file)` is type-unstable and size-unstable because, while you know
it will return a data frame, you don't know what columns it will return or
how many rows it will have. Similarly, `df[[i]]` is not type-stable because
the result depends on the _value_ of `i`. There are many important
functions that can not be made type-stable or size-stable!
With this understanding of type- and size-stability in hand, we'll use them to analyse some base R functions in greater depth and then propose alternatives with better properties.
## `c()` and `vctrs::vec_c()`
In this section we'll compare and contrast `c()` and `vec_c()`. `vec_c()` is both type- and size-stable because it possesses the following invariants:
* `vec_ptype(vec_c(x, y))` equals `vec_ptype_common(x, y)`.
* `vec_size(vec_c(x, y))` equals `vec_size(x) + vec_size(y)`.
`c()` has another undesirable property in that it's not consistent with `unlist()`; i.e., `unlist(list(x, y))` does not always equal `c(x, y)`; i.e., base R has multiple sets of type-coercion rules. I won't consider this problem further here.
I have two goals here:
* To fully document the quirks of `c()`, hence motivating the development
of an alternative.
* To discuss non-obvious consequences of the type- and size-stability above.
### Atomic vectors
If we only consider atomic vectors, `c()` is type-stable because it uses a hierarchy of types: character > complex > double > integer > logical.
```{r}
c(FALSE, 1L, 2.5)
```
`vec_c()` obeys similar rules:
```{r}
vec_c(FALSE, 1L, 2.5)
```
But it does not automatically coerce to character vectors or lists:
```{r, error = TRUE}
c(FALSE, "x")
vec_c(FALSE, "x")
c(FALSE, list(1))
vec_c(FALSE, list(1))
```
### Incompatible vectors and non-vectors
In general, most base methods do not throw an error:
```{r}
c(10.5, factor("x"))
```
If the inputs aren't vectors, `c()` automatically puts them in a list:
```{r}
c(mean, globalenv())
```
For numeric versions, this depends on the order of inputs. Version first is an error, otherwise the input is wrapped in a list:
```{r, error = TRUE}
c(getRversion(), "x")
c("x", getRversion())
```
`vec_c()` throws an error if the inputs are not vectors or not automatically coercible:
```{r, error = TRUE}
vec_c(mean, globalenv())
vec_c(Sys.Date(), factor("x"), "x")
```
### Factors
Combining two factors returns an integer vector:
```{r}
fa <- factor("a")
fb <- factor("b")
c(fa, fb)
```
(This is documented in `c()` but is still undesirable.)
`vec_c()` returns a factor taking the union of the levels. This behaviour is motivated by pragmatics: there are many places in base R that automatically convert character vectors to factors, so enforcing stricter behaviour would be unnecessarily onerous. (This is backed up by experience with `dplyr::bind_rows()`, which is stricter and is a common source of user difficulty.)
```{r}
vec_c(fa, fb)
vec_c(fb, fa)
```
### Date-times
`c()` strips the time zone associated with date-times:
```{r}
datetime_nz <- as.POSIXct("2020-01-01 09:00", tz = "Pacific/Auckland")
c(datetime_nz)
```
This behaviour is documented in `?DateTimeClasses` but is the source of considerable user pain.
`vec_c()` preserves time zones:
```{r}
vec_c(datetime_nz)
```
What time zone should the output have if inputs have different time zones? One option would be to be strict and force the user to manually align all the time zones. However, this is onerous (particularly because there's no easy way to change the time zone in base R), so vctrs chooses to use the first non-local time zone:
```{r}
datetime_local <- as.POSIXct("2020-01-01 09:00")
datetime_houston <- as.POSIXct("2020-01-01 09:00", tz = "US/Central")
vec_c(datetime_local, datetime_houston, datetime_nz)
vec_c(datetime_houston, datetime_nz)
vec_c(datetime_nz, datetime_houston)
```
### Dates and date-times
Combining dates and date-times with `c()` gives silently incorrect results:
```{r}
date <- as.Date("2020-01-01")
datetime <- as.POSIXct("2020-01-01 09:00")
c(date, datetime)
c(datetime, date)
```
This behaviour arises because neither `c.Date()` nor `c.POSIXct()` check that all inputs are of the same type.
`vec_c()` uses a standard set of rules to avoid this problem. When you mix dates and date-times, vctrs returns a date-time and converts dates to date-times at midnight (in the timezone of the date-time).
```{r}
vec_c(date, datetime)
vec_c(date, datetime_nz)
```
### Missing values
If a missing value comes at the beginning of the inputs, `c()` falls back to the internal behaviour, which strips all attributes:
```{r}
c(NA, fa)
c(NA, date)
c(NA, datetime)
```
`vec_c()` takes a different approach treating a logical vector consisting only of `NA` as the `unspecified()` class which can be converted to any other 1d type:
```{r}
vec_c(NA, fa)
vec_c(NA, date)
vec_c(NA, datetime)
```
### Data frames
Because it is *almost always* length-stable, `c()` combines data frames column wise (into a list):
```{r}
df1 <- data.frame(x = 1)
df2 <- data.frame(x = 2)
str(c(df1, df1))
```
`vec_c()` is size-stable, which implies it will row-bind data frames:
```{r}
vec_c(df1, df2)
```
### Matrices and arrays
The same reasoning applies to matrices:
```{r}
m <- matrix(1:4, nrow = 2)
c(m, m)
vec_c(m, m)
```
One difference is that `vec_c()` will "broadcast" a vector to match the dimensions of a matrix:
```{r}
c(m, 1)
vec_c(m, 1)
```
### Implementation
The basic implementation of `vec_c()` is reasonably simple. We first figure out the properties of the output, i.e. the common type and total size, and then allocate it with `vec_init()`, and then insert each input into the correct place in the output.
```{r, eval = FALSE}
vec_c <- function(...) {
args <- compact(list2(...))
ptype <- vec_ptype_common(!!!args)
if (is.null(ptype))
return(NULL)
ns <- map_int(args, vec_size)
out <- vec_init(ptype, sum(ns))
pos <- 1
for (i in seq_along(ns)) {
n <- ns[[i]]
x <- vec_cast(args[[i]], to = ptype)
vec_slice(out, pos:(pos + n - 1)) <- x
pos <- pos + n
}
out
}
```
(The real `vec_c()` is a bit more complicated in order to handle inner and outer names).
## `ifelse()`
One of the functions that motivate the development of vctrs is `ifelse()`. It has the surprising property that the result value is "A vector of the same length and attributes (including dimensions and class) as `test`". To me, it seems more reasonable for the type of the output to be controlled by the type of the `yes` and `no` arguments.
In `dplyr::if_else()` I swung too far towards strictness: it throws an error if `yes` and `no` are not the same type. This is annoying in practice because it requires typed missing values (`NA_character_` etc), and because the checks are only on the class (not the full prototype), it's easy to create invalid output.
I found it much easier to understand what `ifelse()` _should_ do once I internalised the ideas of type- and size-stability:
* The first argument must be logical.
* `vec_ptype(if_else(test, yes, no))` equals
`vec_ptype_common(yes, no)`. Unlike `ifelse()` this implies
that `if_else()` must always evaluate both `yes` and `no` in order
to figure out the correct type. I think this is consistent with `&&` (scalar
operation, short circuits) and `&` (vectorised, evaluates both sides).
* `vec_size(if_else(test, yes, no))` equals
`vec_size_common(test, yes, no)`. I think the output could have the same
size as `test` (i.e., the same behaviour as `ifelse`), but I _think_
as a general rule that your inputs should either be mutually recycling
or not.
This leads to the following implementation:
```{r}
if_else <- function(test, yes, no) {
if (!is_logical(test)) {
abort("`test` must be a logical vector.")
}
c(yes, no) %<-% vec_cast_common(yes, no)
c(test, yes, no) %<-% vec_recycle_common(test, yes, no)
out <- vec_init(yes, vec_size(yes))
vec_slice(out, test) <- vec_slice(yes, test)
vec_slice(out, !test) <- vec_slice(no, !test)
out
}
x <- c(NA, 1:4)
if_else(x > 2, "small", "big")
if_else(x > 2, factor("small"), factor("big"))
if_else(x > 2, Sys.Date(), Sys.Date() + 7)
```
By using `vec_size()` and `vec_slice()`, this definition of `if_else()` automatically works with data.frames and matrices:
```{r}
if_else(x > 2, data.frame(x = 1), data.frame(y = 2))
if_else(x > 2, matrix(1:10, ncol = 2), cbind(30, 30))
```
|
/scratch/gouwar.j/cran-all/cranData/vctrs/vignettes/stability.Rmd
|
---
title: "Prototypes and sizes"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Prototypes and sizes}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r setup, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
```
Rather than using `class()` and `length()`, vctrs has notions of prototype (`vec_ptype_show()`) and size (`vec_size()`). This vignette discusses the motivation for why these alternatives are necessary and connects their definitions to type coercion and the recycling rules.
Size and prototype are motivated by thinking about the optimal behaviour for `c()` and `rbind()`, particularly inspired by data frames with columns that are matrices or data frames.
```{r}
library(vctrs)
```
## Prototype
The idea of a prototype is to capture the metadata associated with a vector without capturing any data. Unfortunately, the `class()` of an object is inadequate for this purpose:
* The `class()` doesn't include attributes. Attributes are important because,
for example, they store the levels of a factor and the timezone of a
`POSIXct`. You cannot combine two factors or two `POSIXct`s without
thinking about the attributes.
* The `class()` of a matrix is "matrix" and doesn't include the type of the
underlying vector or the dimensionality.
Instead, vctrs takes advantage of R's vectorised nature and uses a __prototype__, a 0-observation slice of the vector (this is basically `x[0]` but with some subtleties we'll come back to later). This is a miniature version of the vector that contains all of the attributes but none of the data.
Conveniently, you can create many prototypes using existing base functions (e.g, `double()` and `factor(levels = c("a", "b"))`). vctrs provides a few helpers (e.g. `new_date()`, `new_datetime()`, and `new_duration()`) where the equivalents in base R are missing.
### Base prototypes
`vec_ptype()` creates a prototype from an existing object. However, many base vectors have uninformative printing methods for 0-length subsets, so vctrs also provides `vec_ptype_show()`, which prints the prototype in a friendly way (and returns nothing).
Using `vec_ptype_show()` allows us to see the prototypes base R classes:
* Atomic vectors have no attributes and just display the underlying `typeof()`:
```{r}
vec_ptype_show(FALSE)
vec_ptype_show(1L)
vec_ptype_show(2.5)
vec_ptype_show("three")
vec_ptype_show(list(1, 2, 3))
```
* The prototype of matrices and arrays include the base type and the
dimensions after the first:
```{r}
vec_ptype_show(array(logical(), c(2, 3)))
vec_ptype_show(array(integer(), c(2, 3, 4)))
vec_ptype_show(array(character(), c(2, 3, 4, 5)))
```
* The prototype of a factor includes its levels. Levels are a character vector,
which can be arbitrarily long, so the prototype just shows a hash. If the
hash of two factors is equal, it's highly likely that their levels are also
equal.
```{r}
vec_ptype_show(factor("a"))
vec_ptype_show(ordered("b"))
```
While `vec_ptype_show()` prints only the hash, the prototype object itself does
contain all levels:
```{r}
vec_ptype(factor("a"))
```
* Base R has three key date time classes: dates, date-times (`POSIXct`),
and durations (`difftime)`. Date-times have a timezone, and durations have
a unit.
```{r}
vec_ptype_show(Sys.Date())
vec_ptype_show(Sys.time())
vec_ptype_show(as.difftime(10, units = "mins"))
```
* Data frames have the most complex prototype: the prototype of a data frame
is the name and prototype of each column:
```{r}
vec_ptype_show(data.frame(a = FALSE, b = 1L, c = 2.5, d = "x"))
```
Data frames can have columns that are themselves data frames, making this
a "recursive" type:
```{r}
df <- data.frame(x = FALSE)
df$y <- data.frame(a = 1L, b = 2.5)
vec_ptype_show(df)
```
### Coercing to common type
It's often important to combine vectors with multiple types. vctrs provides a consistent set of rules for coercion, via `vec_ptype_common()`. `vec_ptype_common()` possesses the following invariants:
* `class(vec_ptype_common(x, y))` equals `class(vec_ptype_common(y, x))`.
* `class(vec_ptype_common(x, vec_ptype_common(y, z))` equals
`class(vec_ptype_common(vec_ptype_common(x, y), z))`.
* `vec_ptype_common(x, NULL) == vec_ptype(x)`.
i.e., `vec_ptype_common()` is both commutative and associative (with respect to class) and has an identity element, `NULL`; i.e., it's a __commutative monoid__. This means the underlying implementation is quite simple: we can find the common type of any number of objects by progressively finding the common type of pairs of objects.
Like with `vec_ptype()`, the easiest way to explore `vec_ptype_common()` is with `vec_ptype_show()`: when given multiple inputs, it will print their common prototype. (In other words: program with `vec_ptype_common()` but play with `vec_ptype_show()`.)
* The common type of atomic vectors is computed very similar to the rules of base
R, except that we do not coerce to character automatically:
```{r, error = TRUE}
vec_ptype_show(logical(), integer(), double())
vec_ptype_show(logical(), character())
```
* Matrices and arrays are automatically broadcast to higher dimensions:
```{r}
vec_ptype_show(
array(1, c(0, 1)),
array(1, c(0, 2))
)
vec_ptype_show(
array(1, c(0, 1)),
array(1, c(0, 3)),
array(1, c(0, 3, 4)),
array(1, c(0, 3, 4, 5))
)
```
Provided that the dimensions follow the vctrs recycling rules:
```{r, error = TRUE}
vec_ptype_show(
array(1, c(0, 2)),
array(1, c(0, 3))
)
```
* Factors combine levels in the order in which they appear.
```{r}
fa <- factor("a")
fb <- factor("b")
levels(vec_ptype_common(fa, fb))
levels(vec_ptype_common(fb, fa))
```
* Combining a date and date-time yields a date-time:
```{r}
vec_ptype_show(new_date(), new_datetime())
```
When combining two date times, the timezone is taken from the first input:
```{r}
vec_ptype_show(
new_datetime(tzone = "US/Central"),
new_datetime(tzone = "Pacific/Auckland")
)
```
Unless it's the local timezone, in which case any explicit time zone will
win:
```{r}
vec_ptype_show(
new_datetime(tzone = ""),
new_datetime(tzone = ""),
new_datetime(tzone = "Pacific/Auckland")
)
```
* The common type of two data frames is the common type of each column that
occurs in both data frames:
```{r}
vec_ptype_show(
data.frame(x = FALSE),
data.frame(x = 1L),
data.frame(x = 2.5)
)
```
And the union of the columns that only occur in one:
```{r}
vec_ptype_show(data.frame(x = 1, y = 1), data.frame(y = 1, z = 1))
```
Note that new columns are added on the right-hand side. This is consistent
with the way that factor levels and time zones are handled.
### Casting to specified type
`vec_ptype_common()` finds the common type of a set of vector. Typically, however, what you want is a set of vectors coerced to that common type. That's the job of `vec_cast_common()`:
```{r}
str(vec_cast_common(
FALSE,
1:5,
2.5
))
str(vec_cast_common(
factor("x"),
factor("y")
))
str(vec_cast_common(
data.frame(x = 1),
data.frame(y = 1:2)
))
```
Alternatively, you can cast to a specific prototype using `vec_cast()`:
```{r, error = TRUE}
# Cast succeeds
vec_cast(c(1, 2), integer())
# Cast fails
vec_cast(c(1.5, 2.5), factor("a"))
```
If a cast is possible in general (i.e., double -> integer), but information is lost for a specific input (e.g. 1.5 -> 1), it will generate an error.
```{r, error = TRUE}
vec_cast(c(1.5, 2), integer())
```
You can suppress the lossy cast errors with `allow_lossy_cast()`:
```{r}
allow_lossy_cast(
vec_cast(c(1.5, 2), integer())
)
```
This will suppress all lossy cast errors. Supply prototypes if you want to be specific about the type of lossy cast allowed:
```{r}
allow_lossy_cast(
vec_cast(c(1.5, 2), integer()),
x_ptype = double(),
to_ptype = integer()
)
```
The set of casts should not be more permissive than the set of coercions. This is not enforced but it is expected from classes to follow the rule and keep the coercion ecosystem sound.
## Size
`vec_size()` was motivated by the need to have an invariant that describes the number of "observations" in a data structure. This is particularly important for data frames, as it's useful to have some function such that `f(data.frame(x))` equals `f(x)`. No base function has this property:
* `length(data.frame(x))` equals `1` because the length of a data frame
is the number of columns.
* `nrow(data.frame(x))` does not equal `nrow(x)` because `nrow()` of a
vector is `NULL`.
* `NROW(data.frame(x))` equals `NROW(x)` for vector `x`, so is almost what
we want. But because `NROW()` is defined in terms of `length()`, it returns
a value for every object, even types that can't go in a data frame, e.g.
`data.frame(mean)` errors even though `NROW(mean)` is `1`.
We define `vec_size()` as follows:
* It is the length of 1d vectors.
* It is the number of rows of data frames, matrices, and arrays.
* It throws error for non vectors.
Given `vec_size()`, we can give a precise definition of a data frame: a data frame is a list of vectors where every vector has the same size. This has the desirable property of trivially supporting matrix and data frame columns.
### Slicing
`vec_slice()` is to `vec_size()` as `[` is to `length()`; i.e., it allows you to select observations regardless of the dimensionality of the underlying object. `vec_slice(x, i)` is equivalent to:
* `x[i]` when `x` is a vector.
* `x[i, , drop = FALSE]` when `x` is a data frame.
* `x[i, , , drop = FALSE]` when `x` is a 3d array.
```{r}
x <- sample(1:10)
df <- data.frame(x = x)
vec_slice(x, 5:6)
vec_slice(df, 5:6)
```
`vec_slice(data.frame(x), i)` equals `data.frame(vec_slice(x, i))` (modulo variable and row names).
Prototypes are generated with `vec_slice(x, 0L)`; given a prototype, you can initialize a vector of given size (filled with `NA`s) with `vec_init()`.
### Common sizes: recycling rules
Closely related to the definition of size are the __recycling rules__. The recycling rules determine the size of the output when two vectors of different sizes are combined. In vctrs, the recycling rules are encoded in `vec_size_common()`, which gives the common size of a set of vectors:
```{r}
vec_size_common(1:3, 1:3, 1:3)
vec_size_common(1:10, 1)
vec_size_common(integer(), 1)
```
vctrs obeys a stricter set of recycling rules than base R. Vectors of size 1 are recycled to any other size. All other size combinations will generate an error. This strictness prevents common mistakes like `dest == c("IAH", "HOU"))`, at the cost of occasionally requiring an explicit calls to `rep()`.
```{r, echo = FALSE, fig.cap="Summary of vctrs recycling rules. X indicates an error"}
knitr::include_graphics("../man/figures/sizes-recycling.png", dpi = 300)
```
You can apply the recycling rules in two ways:
* If you have a vector and desired size, use `vec_recycle()`:
```{r}
vec_recycle(1:3, 3)
vec_recycle(1, 10)
```
* If you have multiple vectors and you want to recycle them to the same
size, use `vec_recycle_common()`:
```{r}
vec_recycle_common(1:3, 1:3)
vec_recycle_common(1:10, 1)
```
## Appendix: recycling in base R
The recycling rules in base R are described in [The R Language Definition](https://cran.r-project.org/doc/manuals/r-release/R-lang.html#Recycling-rules) but are not implemented in a single function and thus are not applied consistently. Here, I give a brief overview of their most common realisation, as well as showing some of the exceptions.
Generally, in base R, when a pair of vectors is not the same length, the shorter vector is recycled to the same length as the longer:
```{r}
rep(1, 6) + 1
rep(1, 6) + 1:2
rep(1, 6) + 1:3
```
If the length of the longer vector is not an integer multiple of the length of the shorter, you usually get a warning:
```{r}
invisible(pmax(1:2, 1:3))
invisible(1:2 + 1:3)
invisible(cbind(1:2, 1:3))
```
But some functions recycle silently:
```{r}
length(atan2(1:3, 1:2))
length(paste(1:3, 1:2))
length(ifelse(1:3, 1:2, 1:2))
```
And `data.frame()` throws an error:
```{r, error = TRUE}
data.frame(1:2, 1:3)
```
The R language definition states that "any arithmetic operation involving a zero-length vector has a zero-length result". But outside of arithmetic, this rule is not consistently followed:
```{r, error = TRUE}
# length-0 output
1:2 + integer()
atan2(1:2, integer())
pmax(1:2, integer())
# dropped
cbind(1:2, integer())
# recycled to length of first
ifelse(rep(TRUE, 4), integer(), character())
# preserved-ish
paste(1:2, integer())
# Errors
data.frame(1:2, integer())
```
|
/scratch/gouwar.j/cran-all/cranData/vctrs/vignettes/type-size.Rmd
|
#' Launches the web-based GUI for visualizing time series
#'
#' Launches the web-based GUI for visualizing a collection of time series in a
#' web browser.
#'
#' The **vctsfr** package provides a Shiny-based GUI to visualize collections of
#' time series and their forecasts. The main features of the GUI are:
#'
#' * It allows you to easily navigate through the different series.
#' * You can select which forecasting methods are displayed.
#' * In the case you display a single forecasting method with associated
#' prediction intervals, you can select the prediction interval to display.
#' * Forecasting accuracy measures are displayed.
#'
#' @inheritParams plot_collection
#'
#' @return Nothing
#' @export
#'
#' @examplesIf interactive()
#' # create a collection of two time series and visualize them
#' c <- list(ts_info(USAccDeaths), ts_info(ldeaths))
#' GUI_collection(c)
GUI_collection <- function(collection) {
r <- check_time_series_collection(collection)
if (r != "OK")
stop(paste("Error in 'collection' parameter:", r))
# accuracy measures
am <- list(RMSE = function(fut, fore, historical = NULL) sqrt(mean((fut-fore)^2)),
MAPE = function(fut, fore, historical = NULL) mean(abs((fut-fore)/fut))*100,
MAE = function(fut, fore, historical = NULL) mean(abs(fut-fore)),
ME = function(fut, fore, historical = NULL) mean(fut-fore),
MPE = function(fut, fore, historical = NULL) mean((fut-fore)/fut)*100,
sMAPE = function(fut, fore, historical = NULL) mean(200*abs(fore-fut)/(abs(fore)+abs(fut))),
MASE = function(fut, fore, historical = NULL) {
f <- stats::frequency(historical)
mean(abs(fore-fut)) / mean(abs(diff(historical, lag = f)))
}
)
ui <- shiny::fluidPage(
shiny::titlePanel("Visualize time series"),
shiny::sidebarLayout(
shiny::sidebarPanel(
shiny::numericInput("number",
paste0("Time series number (max = ", length(collection), ")"),
value = 1,
min = 1,
max = length(collection)),
shiny::checkboxInput("sdp", "Show data points?", value = TRUE),
shiny::br(),
shiny::uiOutput("models"),
shiny::br(),
shiny::uiOutput("pi")
),
shiny::mainPanel(shiny::plotOutput("plot"),
shiny::br(),
shiny::uiOutput("accu_message"),
shiny::tableOutput("accuracy"))
)
)
server <- function(input, output) {
output$models <- shiny::renderUI({
pred <- collection[[input$number]]
if ("forecasts" %in% names(pred)) {
names <- sapply(pred$forecasts, function(f) f$name)
if (is.null(input$model)) {
selected <- NULL
} else if (all(input$model %in% names)) {
selected <- input$model
} else {
selected <- names
}
shiny::checkboxGroupInput("model",
"Select models",
choices = names,
selected = selected
)
}
})
output$pi <- shiny::renderUI({
pred <- collection[[input$number]]
if ("forecasts" %in% names(pred)) {
if (!is.null(input$model) && length(input$model) == 1) {
forecasting_names <- sapply(pred$forecasts, function(x) x$name)
position <- which(input$model == forecasting_names)
if ("pi" %in% names(pred$forecasts[[position]])) {
levels <- sapply(pred$forecasts[[position]]$pi, function(p) p$level)
shiny::radioButtons("pi", "Select prediction interval", c("none", paste(levels)))
}
}
}
})
output$plot <- shiny::renderPlot({
if (is.null(input$model)) {
collection[[input$number]]$forecasts <- NULL
p <- plot_collection(collection, number = input$number, sdp = input$sdp)
} else {
level <- if(length(input$model) == 1 && !is.null(input$pi) && input$pi != "none") as.numeric(input$pi) else NULL
p <- plot_collection(collection,
number = input$number,
methods = input$model,
level = level,
sdp = input$sdp
)
}
p + ggplot2::ggtitle(paste("Time series", collection[[input$number]]$name)) +
ggplot2::theme(plot.title = ggplot2::element_text(face = "bold"))
}, res = 96)
output$accu_message <- shiny::renderUI({
pred <- collection[[input$number]]
if (!is.null(pred$future) && !is.null(input$model)) {
shiny::h4(shiny::strong("Forecast accuracy measures"))
}
})
output$accuracy <- shiny::renderTable({
pred <- collection[[input$number]]
if (!is.null(pred$future) && !is.null(input$model)) {
d <- NULL
for(a_m in am) {
d <- cbind(d, compute_error(a_m, pred, input$model))
}
d <- data.frame(d)
colnames(d) <- names(am)
row.names(d) <- input$model
d
}
}, rownames = TRUE)
}
shiny::shinyApp(ui, server)
}
compute_error <- function(f, information, models) {
result <- numeric(length = length(models))
for (ind in seq_along(models)) {
name <- models[ind]
forecasting_names <- sapply(information$forecasts, function(x) x$name)
position <- which(name == forecasting_names)
result[ind] <- f(information$future, information$forecasts[[position]]$forecast,
information$historical)
}
result
}
|
/scratch/gouwar.j/cran-all/cranData/vctsfr/R/GUI_collection.R
|
#' Create a `ggplot` object associated with a time series belonging to a
#' collection.
#'
#' Apart from the time series, future values and forecasts for the
#' future values form part of the `ggplot` object.
#'
#' The `collection` parameter must be a list. Each component of the list stores
#' a time series and, optionally, its future values, forecasts for the future
#' values and prediction intervals for the forecasts. Each component should have
#' been created using the [ts_info()] function.
#'
#' In the example section you can see an example of a collection of time series.
#' If the `collection` parameter is not specified correctly, a proper message is
#' shown.
#'
#' @param collection a list with the collection of time series. Each component
#' of the list must have been built with the [ts_info()] function.
#' @param number an integer. The number of the time series. It should be a value
#' between 1 and `length(collection)`.
#' @param methods NULL (default) or a character vector indicating the names of
#' the forecasting methods to be displayed.
#' @param level NULL (default) or a number in the interval (0, 100) indicating
#' the level of the prediction interval to be shown. This parameter in
#' considered only when just one forecasting method is plotted and the
#' forecasting method has a prediction interval with the specified level.
#' @param sdp logical. Should data points be shown in the plot? (default value
#' `TRUE`)
#'
#' @return The `ggplot` object representing the time series and its forecast.
#' @export
#'
#' @seealso [ts_info()] function to see how to build the components of the
#' `collection` parameter.
#' @examples
#' # create a collection of two time series and plot both time series
#' c <- list(ts_info(USAccDeaths), ts_info(ldeaths))
#' plot_collection(c, number = 1)
#' plot_collection(c, number = 2, sdp = FALSE)
#'
#' # create a collection of one time series with future values and forecasts
#' if (require(forecast)) {
#' c <- vector(2, mode = "list")
#' timeS <- window(USAccDeaths, end = c(1977, 12))
#' f <- window(USAccDeaths, start = c(1978, 1))
#' ets_fit <- ets(timeS)
#' ets_pred <- forecast(ets_fit, h = length(f), level = 90)
#' mean_pred <- meanf(timeS, h = length(f), level = 90)
#' c[[1]] <- ts_info(timeS, future = f,
#' prediction_info("ES", ets_pred$mean,
#' pi_info(90, ets_pred$lower, ets_pred$upper)),
#' prediction_info("Mean", mean_pred$mean,
#' pi_info(90, mean_pred$lower, mean_pred$upper))
#' )
#' timeS <- ts(rnorm(30, sd = 3))
#' f <- rnorm(5, sd = 3)
#' rw <- rwf(timeS, h = length(f), level = 80)
#' mean <- meanf(timeS, h = length(f), level = 90)
#' c[[2]] <- ts_info(timeS, future = f,
#' prediction_info("Random Walk", rw$mean,
#' pi_info(80, rw$lower, rw$upper)),
#' prediction_info("Mean", mean$mean,
#' pi_info(90, mean$lower, mean$upper))
#' )
#' plot_collection(c, number = 1)
#' }
#' if (require("forecast"))
#' plot_collection(c, number = 2)
#' if (require("forecast"))
#' plot_collection(c, number = 2, methods = "Mean") # just plot a forecasting method
#' if (require("forecast"))
#' plot_collection(c, number = 2, methods = "Random Walk", level = 80)
plot_collection <- function(collection, number, methods = NULL, level = NULL, sdp = TRUE) {
# check collection parameter
r <- check_time_series_collection(collection)
if (r != "OK")
stop(paste("Error in 'collection' parameter:", r))
# Check number parameter
if (! (is.numeric(number) && number >= 1 && number <= length(collection)))
stop("'number' parameter should be a valid index in collection")
# Check methods parameter
if (! (is.null(methods) || is.character(methods)))
stop("methods parameter should be a character vector")
if(!is.null(methods) && !("forecasts" %in% names(collection[[number]]))) {
m <- paste("methods parameter should contain names of forecasting methods in series number", number)
stop(m)
}
if(!is.null(methods) && ("forecasts" %in% names(collection[[number]]))) {
forecasting_names <- sapply(collection[[number]]$forecasts, function(x) x$name)
if (!all(methods %in% forecasting_names)){
m <- paste("all the names of method parameter should be existing forecasting methods in series number", number)
stop(m)
}
}
# check level parameter
if (!is.null(level) && (!is.numeric(level) || length(level) > 1 || level <= 0 || level >= 100))
stop("Parameter level should be a scalar number in the interval (0, 100)")
# is there only one forecasting method to plot?
only_one_method <- ("forecasts" %in% names(collection[[number]])) &&
((!is.null(methods) && length(methods) == 1) ||
is.null(methods) && length(collection[[number]]$forecast) == 1)
if (!is.null(level) && !only_one_method)
stop("level parameter should only be used when plotting just one forecasting method")
if (!is.null(level) && only_one_method) {
position <- if (is.null(methods)) 1 else which(methods == forecasting_names)
if (!("pi" %in% names(collection[[number]]$forecasts[[position]]))) {
stop("level parameter is used and the forecasting method has no prediction intervals")
} else {
levels <- sapply(collection[[number]]$forecasts[[position]]$pi, function(p) p$level)
if (!(level %in% levels)) {
m <- paste0("level ", level,
" is not included in the prediction interval levels of the forecasting method")
m <- paste0(m, "\n current levels: ", paste(levels, collapse = " "))
stop(m)
}
}
}
if (only_one_method && !is.null(level)) {
position <- if (is.null(methods)) 1 else which(methods == forecasting_names)
levels <- sapply(collection[[number]]$forecasts[[position]]$pi, function(p) p$level)
position2 <- which(level == levels)
return(plot_ts(collection[[number]]$historical,
future = collection[[number]]$future,
prediction = collection[[number]]$forecast[[position]]$forecast,
method = collection[[number]]$forecast[[position]]$name,
lpi = collection[[number]]$forecast[[position]]$pi[[position2]]$lpi,
upi = collection[[number]]$forecast[[position]]$pi[[position2]]$upi,
level = level
))
}
if ("forecasts" %in% names(collection[[number]])) {
p <- list()
for (pred in collection[[number]]$forecasts) {
if (!is.null(methods) && !(pred$name %in% methods)) next
p[[length(p) + 1]] <- pred$forecast
names(p)[[length(p)]] <- pred$name
}
} else {
p <- NULL
}
plot_predictions(collection[[number]]$historical,
future = collection[[number]]$future,
predictions = p,
sdp = sdp
)
}
#' Check that a collection of time series is properly formatted
#'
#' This function checks that an object holding a collection of time series,
#' their future values and their forecasts has the correct format. This kind of
#' objects are used in function [plot_collection()]. A collection of time series
#' should be a list compounded of objects of class `ts_info`, which are built
#' using the [ts_info()] function.
#'
#' @param collection a list representing a collection of time series as
#' described in [plot_collection()].
#'
#' @return a character string with value `"OK"` if the object is properly
#' formatted. Otherwise, the character string indicates the first error found
#' in the object's format.
#' @export
#'
#' @examples
#' c <- list(ts_info(USAccDeaths), ts_info(ldeaths))
#' check_time_series_collection(c)
check_time_series_collection <- function(collection) {
if (!is.list((collection)))
return("A time series collection should be a list")
for (ind in seq_along(collection)) {
if (! methods::is(collection[[ind]], "ts_info")) {
return(paste0("Component [[", ind, "]] of collection should be of class ts_info"))
}
}
return("OK")
}
|
/scratch/gouwar.j/cran-all/cranData/vctsfr/R/plot_collection.R
|
#'Creates a ggplot object with a time series and some forecasts
#'
#'Create a `ggplot` object with a time series and, optionally, some future
#'values of the time series and several forecast for those future values.
#'
#'If \code{future} or the forecasts in the \code{prediction} list are vectors
#'then they are supposed to start after the last data of the time series.
#'
#'@inheritParams plot_ts
#'@param predictions NULL (default) or a named list containing the predictions
#' for the future values. Each component of the list should contain a vector or
#' an object of class \code{ts} representing a forecast, the name of the
#' component should be the name of the forecasting method.
#'
#'@return The `ggplot` object representing the time series and its forecast.
#'@export
#'
#' @examples
#' # plot a time series, its future values and two forecasts
#' ts <- window(USAccDeaths, end = c(1977, 12))
#' f <- window(USAccDeaths, start = c(1978, 1))
#' prediction1 <- rep(mean(ts), 12)
#' prediction2 <- as.vector(window(ts, start = c(1977, 1)))
#' p <- list(Mean = prediction1, Naive = prediction2)
#' plot_predictions(ts, future = f, predictions = p)
plot_predictions <- function(ts, future = NULL, predictions = NULL, sdp = TRUE) {
# check ts parameter
if(! stats::is.ts(ts))
stop("Parameter ts should be of class ts")
check_vector_ts(future, "future") # check future parameter
# check predictions parameter
if (!is.null(predictions)) {
if (!is.list(predictions))
stop("Predictions parameter should be a named list with the different forecasts")
if (is.null(names(predictions)) || any(names(predictions) == ""))
stop("All the elements in the list predictions should have a name")
for (ind in seq_along(predictions)) {
if(! (stats::is.ts(predictions[[ind]]) || is.numeric(predictions[[ind]]) ||
is.integer(predictions[[ind]]))) {
msg <- paste("Forecast", names(predictions)[ind],
"should be a numeric vector or an object of class ts")
stop(msg)
}
}
}
# check sdp parameter
if(! is.logical(sdp))
stop("Parameter sdp should be a logical value")
df <- data.frame(
x = as.vector(stats::time(ts)),
y = as.vector(ts),
type = "Historical"
)
df <- rbind(df, add_ts(future, ts, "Future"))
for (ind in seq_along(predictions))
df <- rbind(df, add_ts(predictions[[ind]], ts, names(predictions)[ind]))
x <- y <- type <- NULL # to avoid notes
p <- ggplot2::ggplot(df, mapping = ggplot2::aes(x, y)) +
ggplot2::geom_line(ggplot2::aes(color = type))
if (sdp)
p <- p + ggplot2::geom_point(mapping = ggplot2::aes(color = type), size = 1)
p <- p + ggplot2::labs(color = "Series", x = "Time", y = NULL)
breaks <- c("Historical", "Future", names(predictions))
my_col <- c("#000000", "#0000DD", "#E69F00", "#009E73", "#F0E442", "#D55E00",
"#CC79A7", "#56B4E9")
colours <- my_col[seq_along(breaks)]
names(colours) <- breaks
p <- p + ggplot2::scale_colour_manual(values = colours, breaks = breaks)
p
}
|
/scratch/gouwar.j/cran-all/cranData/vctsfr/R/plot_predictions.R
|
#' Create a ggplot object with a time series and forecast
#'
#' Create a `ggplot` object associated with a time series and, optionally, its
#' future values, a forecast for its future values and a prediction interval of
#' the forecast.
#'
#' If \code{future} or \code{prediction} are vectors then they are supposed to
#' start after the last data of the time series.
#'
#' @param ts a time series of class \code{ts}.
#' @param future NULL (default) or a time series of class \code{ts} or a vector.
#' Future values of the time series.
#' @param prediction NULL (default) or a time series of class \code{ts} or a
#' vector. Forecast of the future values of the time series.
#' @param method NULL (default) a character string with the name of the method
#' used to forecast the future values of the time series. This name will
#' appear in the legend.
#' @param lpi NULL (default) or a time series of class \code{ts} or a vector.
#' Lower limit of a prediction interval for the `prediction` parameter.
#' @param upi NULL (default) or a time series of class \code{ts} or a vector.
#' Upper limit of a prediction interval for the `prediction` parameter.
#' @param level NULL (default) a number in the interval (0, 100) indicating the
#' level of the prediction interval.
#' @param sdp logical. Should data points be shown? (default value `TRUE`)
#'
#' @return The `ggplot` object representing the time series and its forecast.
#' @export
#'
#' @examples
#' library(ggplot2)
#' plot_ts(USAccDeaths) # plot a time series
#'
#' # plot a time series, not showing data points
#' plot_ts(USAccDeaths, sdp = FALSE)
#'
#' # plot a time series, its future values and a prediction
#' ts <- window(USAccDeaths, end = c(1977, 12))
#' f <- window(USAccDeaths, start = c(1978, 1))
#' p <- ts(window(USAccDeaths, start = c(1976, 1), end = c(1976, 12)),
#' start = c(1978, 1),
#' frequency = 12
#' )
#' plot_ts(ts, future = f, prediction = p)
#'
#' # plot a time series and a prediction
#' plot_ts(USAccDeaths, prediction = rep(mean(USAccDeaths), 12),
#' method = "Mean")
#'
#' # plot a time series, a prediction and a prediction interval
#' if (require(forecast)) {
#' timeS <- window(USAccDeaths, end = c(1977, 12))
#' f <- window(USAccDeaths, start = c(1978, 1))
#' ets_fit <- ets(timeS)
#' p <- forecast(ets_fit, h = length(f), level = 90)
#' plot_ts(timeS, future = f, prediction = p$mean, method = "ES",
#' lpi = p$lower, upi = p$upper, level = 90
#' )
#' }
plot_ts <- function(ts, future = NULL, prediction = NULL, method = NULL, lpi = NULL,
upi = NULL, level = NULL, sdp = TRUE) {
# check ts parameter
if(! stats::is.ts(ts))
stop("Parameter ts should be of class ts")
check_vector_ts(future, "future") # check future parameter
check_vector_ts(prediction, "prediction") # check prediction parameter
# check different lengths of future and prediction
if (!is.null(future) && !is.null(prediction) && length(future) != length(prediction))
warning("Length of prediction and future parameters are different")
# check method parameter
if (! (is.null(method) || (is.character(method) && length(method) == 1)))
stop("method parameter should be a character string")
check_vector_ts(upi, "upi") # check upi parameter
check_vector_ts(lpi, "lpi") # check lpi parameter
# check different lengths of upi and lpi
if (length(upi) != length(lpi))
warning("upi and lpi parameters should have the same length")
# check different lengths of prediction and upi
if (!is.null(upi) && length(upi) != length(prediction))
warning("prediction and upi parameters should have the same length")
# check different lengths of prediction and lpi
if (!is.null(lpi) && length(lpi) != length(prediction))
warning("prediction and lpi parameters should have the same length")
# Check level parameter
if (!is.null(level) && (!is.numeric(level) || length(level) > 1 || level <= 0 || level >= 100))
stop("Parameter level should be a scalar number in the interval (0, 100)")
if (is.null(level) && !is.null(lpi))
stop("If the prediction interval is specified, the level parameter should be specified")
# check sdp parameter
if(! is.logical(sdp))
stop("Parameter sdp should be a logical value")
df <- data.frame(
x = as.vector(stats::time(ts)),
y = as.vector(ts),
type = "Historical"
)
if (is.null(method))
method <- "Forecast"
name_PI <- paste0(if (is.null(level)) "" else level, "% PI")
df_f <- add_ts(future, ts, "Future")
df_p <- add_ts(prediction, ts, method)
df_upi <- add_ts(upi, ts, name_PI)
df_lpi <- add_ts(lpi, ts, "Lower PI")
df <- rbind(df, df_f, df_p, df_upi)
x <- y <- type <- NULL # to avoid notes
p <- ggplot2::ggplot(df, ggplot2::aes(x, y))
p <- p + ggplot2::geom_line(ggplot2::aes(color = type))
# Lower pi
if (!is.null(lpi)) {
p <- p + ggplot2::geom_line(ggplot2::aes(x, y), data = df_lpi, colour = "pink")
if (sdp)
p <- p + ggplot2::geom_point(ggplot2::aes(x, y), data = df_lpi, colour = "pink", size = 1, alpha = 0.2)
}
if (!is.null(upi) && !is.null(lpi)) {
limits <- data.frame(x = df_upi$x, y = df_p$y, upi = upi, lpi = lpi)
p <- p + ggplot2::geom_ribbon(data = limits, ggplot2::aes(x = x, ymax = upi, ymin = lpi), fill = "pink", alpha = 0.2)
}
if (sdp) {
p <- p + ggplot2::geom_point(size = 1, ggplot2::aes(color = type))
}
p <- p + ggplot2::labs(x = "Time", y = NULL, color = "Series")
breaks <- c("Historical", "Future", method, name_PI)
colours <- c("black", my_colours("blue"), my_colours("red"), "pink")
names(colours) <- c("Historical", "Future", method, name_PI)
p <- p + ggplot2::scale_colour_manual(values = colours, breaks = breaks)
if (is.null(future) && is.null(prediction))
p <- p + ggplot2::guides(colour = "none")
p
}
# Check if a parameter is a vector or object of class ts,
check_vector_ts <- function(v, nombre) {
if(! (is.null(v) || stats::is.ts(v) || is.numeric(v) || is.integer(v))) {
msg <- paste("Parameter", nombre, "should be a numeric vector or an object of class ts")
stop(msg)
}
}
# Add time series v (after ts) of type type to a data frame
add_ts <- function(v, ts, type) {
if (is.null(v))
return(NULL)
if(!stats::is.ts(v))
v <- v2ts(ts, v)
data.frame(
x = as.vector(stats::time(v)),
y = as.vector(v),
type = type
)
}
# Convert a vector into a time series
# The conversion is such that v starts right after time series ts
v2ts <- function(ts, v) {
temp <- stats::ts(1:2,
start = stats::end(ts),
frequency = stats::frequency(ts)
)
stats::ts(v,
start = stats::end(temp),
frequency = stats::frequency(ts)
)
}
my_colours <- function(name) {
col_l <- list("blue" = "#000099",
"red" = "#CC0000",
"green" = "#339900",
"orange" = "#CC79A7"
)
return(col_l[[name]])
}
|
/scratch/gouwar.j/cran-all/cranData/vctsfr/R/plot_ts.R
|
#' Create an object with information about a time series
#'
#' The information about the time series is compounded of the time series and,
#' optionally, its future values and forecasts for those future values (and
#' prediction intervals for those forecasts).
#'
#' @param historical a time series of class \code{ts} with the historical values
#' of the series.
#' @param ... forecasts for the future values of the time series. A forecast
#' must have been built with the [prediction_info()] function. See the
#' examples section.
#' @param future NULL (default) or a time series of class \code{ts} or a vector.
#' The future values of the time series (possibly to be forecast).
#' @param name NULL (default) or a character string with information about the
#' time series. Typically, its name.
#'
#' @return An object of class `ts_info`. It is a list containing all the
#' information supplied to the function.
#' @export
#'
#' @seealso [prediction_info()] for how to create forecasts.
#' @examples
#' # only information about a time series
#' info <- ts_info(USAccDeaths)
#'
#' # Information about a time series and its future values
#' info2 <- ts_info(ts(rnorm(50)), future = rnorm(10))
#'
#' # Information about a time series, its future values and a forecast
#' if (require("forecast")) {
#' t <- ts(rnorm(50))
#' f <- rnorm(10)
#' mf <- meanf(t, level = 95)
#' info3 <- ts_info(t, future = f,
#' prediction_info("mean", mf$mean,
#' pi_info(95, mf$lower, mf$upper)
#' )
#' )
#' }
ts_info <- function(historical, ..., future = NULL, name = NULL) {
# check historical parameter
if(! stats::is.ts(historical))
stop("Parameter historical should be of class ts")
# check future parameter
if(! (is.null(future) || stats::is.ts(future) || is.numeric(future) ||
is.integer(future))) {
stop("Parameter future should be a numeric vector or an object of class ts")
}
# check ... parameter
l <- list(...)
for (x in l) {
if (! methods::is(x, "pred_info"))
stop("All the ... parameters should be of class pred_info")
}
# check name parameter
if (! (is.null(name) || (is.character(name) && length(name) == 1)))
stop("name parameter should be a character string")
info <- list(historical = historical, name = name, future = future)
if (length(l) > 0)
info$forecasts <- l
class(info) <- "ts_info"
info
}
#' Create an object with a prediction about the future values of a time series
#'
#' The object created contains a forecast and, optionally, prediction intervals
#' for the forecast.
#'
#' @param name a character indicating the name of the method used to forecast.
#' @param forecast a time series of class \code{ts} or a vector. It is a
#' prediction for the future values of a time series.
#' @param ... prediction intervals for the forecast. These prediction intervals
#' must have been built with the [pi_info()] function.
#'
#' @return an object of class `pred_info`. A list with the information supplied
#' to the function.
#' @export
#'
#' @seealso [pi_info()] for how to create prediction intervals.
#' @examples
#' if (require("forecast")) {
#' time_series <- ts(rnorm(40))
#' f <- meanf(time_series, level = 95)
#' info <- prediction_info("mean", f$mean, pi_info(95, f$lower, f$upper))
#' }
prediction_info <- function(name, forecast, ...) {
# check name parameter
if (! (is.character(name) && length(name) == 1))
stop("Parameter name should be a character")
# check prediction parameter
if(! (is.null(forecast) || stats::is.ts(forecast) || is.numeric(forecast) ||
is.integer(forecast))) {
stop("Parameter forecast should be a numeric vector or an object of class ts")
}
# check ... parameter
l <- list(...)
for (x in l) {
if (! methods::is(x, "pi_info"))
stop("All the ... parameters should be of class pi_info")
if (length(forecast) != length(x$lpi))
stop("The length of a prediction interval is different from the length of the forecast")
}
pred <- list(name = name, forecast = forecast)
if (length(l) > 0)
pred$pi <- l
class(pred) <- "pred_info"
pred
}
#' Create a prediction interval object
#'
#' The object created represents a prediction interval for the forecast of the
#' future values of a time series.
#'
#' @param level a number in the interval (0, 100) indicating the level of the
#' prediction interval.
#' @param lpi a time series of class \code{ts} or a vector. Lower limit of a
#' prediction interval.
#' @param upi a time series of class \code{ts} or a vector. Upper limit of a
#' prediction interval.
#'
#' @return An object of class `pi_info`. It is a list containing all the
#' information supplied to the function.
#'
#' @seealso [prediction_info()] which uses this function to specify prediction
#' intervals.
#' @export
#'
#' @examples
#' if (require("forecast")) {
#' time_series <- ts(rnorm(40))
#' f <- meanf(time_series, level = 95)
#' info <- pi_info(95, f$lower, f$upper)
#' }
pi_info <- function(level, lpi, upi) {
# Check level parameter
if(!is.numeric(level) || length(level) > 1 || level <= 0 || level >= 100)
stop("Parameter level should be a scalar number in the range (0, 100)")
# Check lpi parameter
if(! (stats::is.ts(lpi) || is.numeric(lpi) || is.integer(lpi)))
stop("Parameter lpi should be a numeric vector or an object of class ts")
# Check upi parameter
if(! (stats::is.ts(upi) || is.numeric(upi) || is.integer(upi)))
stop("Parameter upi should be a numeric vector or an object of class ts")
# check different lengths of prediction and upi
if (length(upi) != length(lpi))
stop("Lower and upper prediction interval should have the same length")
structure(list(level = level, lpi = lpi, upi = upi), class = "pi_info")
}
|
/scratch/gouwar.j/cran-all/cranData/vctsfr/R/ts_info.R
|
## ----include = FALSE----------------------------------------------------------
knitr::opts_chunk$set(
fig.width = 6,
fig.heigth = 2,
collapse = TRUE,
comment = "#>"
)
## -----------------------------------------------------------------------------
library(vctsfr)
plot_ts(USAccDeaths) # plotting a time series
## -----------------------------------------------------------------------------
plot_ts(USAccDeaths, sdp = FALSE)
## -----------------------------------------------------------------------------
library(forecast)
ets_fit <- ets(USAccDeaths)
ets_f <- forecast(ets_fit, h = 12)
plot_ts(USAccDeaths, prediction = ets_f$mean, method = "ets")
## -----------------------------------------------------------------------------
library(forecast)
ets_fit <- ets(USAccDeaths)
ets_f <- forecast(ets_fit, h = 12, level = 90)
plot_ts(USAccDeaths,
prediction = ets_f$mean,
method = "ets",
lpi = ets_f$lower,
upi = ets_f$upper,
level = 90
)
## -----------------------------------------------------------------------------
timeS <- window(USAccDeaths, end = c(1977, 12))
fut <- window(USAccDeaths, start = c(1978, 1))
ets_fit <- ets(timeS)
ets_f <- forecast(ets_fit, h = length(fut), level = 80)
plot_ts(timeS,
future = fut,
prediction = ets_f$mean,
method = "ets",
lpi = ets_f$lower,
upi = ets_f$upper,
level = 80
)
## -----------------------------------------------------------------------------
timeS <- window(USAccDeaths, end = c(1977, 12)) # historical values
fut <- window(USAccDeaths, start = c(1978, 1)) # "future" values
ets_fit <- ets(timeS) # exponential smoothing fit
ets_f <- forecast(ets_fit, h = length(fut)) # exponential smoothing forecast
arima_fit <- auto.arima(timeS) # ARIMA fit
arima_f <- forecast(arima_fit, h = length(fut)) # ARIMA forecast
plot_predictions(timeS, future = fut,
predictions = list(ets = ets_f$mean, arima = arima_f$mean)
)
## -----------------------------------------------------------------------------
collection1 <- list(ts_info(USAccDeaths), ts_info(UKDriverDeaths))
## -----------------------------------------------------------------------------
library(Mcomp)
# select the industry, quarterly series from M1 competition (18 series)
M1_quarterly <- subset(M1, 4, "industry")
# build the collection
collection2 <- vector("list", length = length(M1_quarterly))
for (ind in seq_along(M1_quarterly)) {
timeS <- M1_quarterly[[ind]]$x # time series
name <- M1_quarterly[[ind]]$st # time series's name
fut <- M1_quarterly[[ind]]$xx # future values
ets_fit <- ets(timeS) # ES fit
ets_for <- forecast(ets_fit, h = length(fut)) # ES forecast
collection2[[ind]] <- ts_info(timeS,
prediction_info("ets", ets_for$mean),
future = fut,
name = name
)
}
## -----------------------------------------------------------------------------
collection3 <- vector("list", length = length(M1_quarterly))
for (ind in seq_along(M1_quarterly)) {
t <- M1_quarterly[[ind]]$x # time series
name <- M1_quarterly[[ind]]$st # time series's name
f <- M1_quarterly[[ind]]$xx # "future" values
ets_fit <- ets(t) # ES fit
ets_f <- forecast(ets_fit, h = length(f), level = 90) # ES forecast
arima_fit <- auto.arima(t) # ARIMA fit
arima_f <- forecast(arima_fit, h = length(f), # ARIMA forecast
level = c(80, 90)
)
collection3[[ind]] <- ts_info(t,
future = f,
prediction_info("ets",
ets_f$mean,
pi_info(90,
ets_f$lower,
ets_f$upper)
),
prediction_info("arima",
arima_f$mean,
pi_info(80,
arima_f$lower[, 1],
arima_f$upper[, 1]
),
pi_info(90,
arima_f$lower[, 2],
arima_f$upper[, 2]
)
),
name = name)
}
## -----------------------------------------------------------------------------
plot_collection(collection3, number = 3)
## -----------------------------------------------------------------------------
plot_collection(collection3, number = 3, methods = "ets")
## -----------------------------------------------------------------------------
plot_collection(collection3, number = 3, methods = "arima", level = 90)
## ----eval=FALSE---------------------------------------------------------------
# GUI_collection(collection3)
|
/scratch/gouwar.j/cran-all/cranData/vctsfr/inst/doc/vctsfr.R
|
---
title: "vctsfr"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{vctsfr}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r, include = FALSE}
knitr::opts_chunk$set(
fig.width = 6,
fig.heigth = 2,
collapse = TRUE,
comment = "#>"
)
```
In this document we present the **vctsfr** package, which can be an useful tool for those involved in time series forecasting because it allows you to visually compare the predictions of several forecasting models. The **vctsfr** package is especially convenient when you want to visually compare the predictions of several forecasting methods across a collection of time series.
The **vctsfr** package makes it easy the visualization of collections of time series and, optionally, their future values and forecasts for those future values. The forecasts can include prediction intervals. This package is particularly useful when you have forecasts (maybe from different models) for several time series and you want to display them in order to compare their results.
This package arises from a need of her authors. Frequently, we used several forecasting methods to predict the future values of collections of time series (typically belonging to time series competitions). The usual way of comparing the performance of the forecasting methods is to compute a global measure of forecast accuracy for every method based on all its forecasts for all the series of the competition. However, we miss a way of visually compare the performance of different methods over a particular series. This package fills this gap.
This package also facilitates the visualization of just a collection of time series (without forecasts).
## Visualizing a single time series
If you only want to display a single time series and, optionally, information about its future values and/or a forecast for its future values you can use the `plot_ts()` function. Let us see how it works.
```{r}
library(vctsfr)
plot_ts(USAccDeaths) # plotting a time series
```
By default, `plot_ts()` shows the data points in the time series. However, you can omit them with the `sdp` parameter:
```{r}
plot_ts(USAccDeaths, sdp = FALSE)
```
Let us now display the same time series and a forecast for its next 12 months using the exponential smoothing model implemented in the **forecast** package (`ets()` function):
```{r}
library(forecast)
ets_fit <- ets(USAccDeaths)
ets_f <- forecast(ets_fit, h = 12)
plot_ts(USAccDeaths, prediction = ets_f$mean, method = "ets")
```
If the forecasting method computes prediction intervals, they can be displayed. For example, let's add a 90% prediction interval to the previous forecast:
```{r}
library(forecast)
ets_fit <- ets(USAccDeaths)
ets_f <- forecast(ets_fit, h = 12, level = 90)
plot_ts(USAccDeaths,
prediction = ets_f$mean,
method = "ets",
lpi = ets_f$lower,
upi = ets_f$upper,
level = 90
)
```
Finally, the actual values that are predicted can also be displayed:
```{r}
timeS <- window(USAccDeaths, end = c(1977, 12))
fut <- window(USAccDeaths, start = c(1978, 1))
ets_fit <- ets(timeS)
ets_f <- forecast(ets_fit, h = length(fut), level = 80)
plot_ts(timeS,
future = fut,
prediction = ets_f$mean,
method = "ets",
lpi = ets_f$lower,
upi = ets_f$upper,
level = 80
)
```
Summarizing, the `plot_ts()` function is useful to visualize a time series and, optionally, a forecast for its future values.
In all the functions of the **vctsfr** package the time series parameter, i.e. the historical values of the series, is specified as an object of class `ts`. The future values, forecasts and prediction intervals can be specified as a numeric vector or as an object of class `ts`.
## Visualizing several forecasts
When you want to compare several forecasts for the future values of a time series you can use the function `plot_predictions()`. The forecasts are passed to the function as a list, each component of the list is a forecast and the name of the component is the name of the forecasting method. Let us see an example in which, given a time series, the forecasts for its future values, using the ARIMA and exponential smoothing models implemented in the **forecast** package, are displayed:
```{r}
timeS <- window(USAccDeaths, end = c(1977, 12)) # historical values
fut <- window(USAccDeaths, start = c(1978, 1)) # "future" values
ets_fit <- ets(timeS) # exponential smoothing fit
ets_f <- forecast(ets_fit, h = length(fut)) # exponential smoothing forecast
arima_fit <- auto.arima(timeS) # ARIMA fit
arima_f <- forecast(arima_fit, h = length(fut)) # ARIMA forecast
plot_predictions(timeS, future = fut,
predictions = list(ets = ets_f$mean, arima = arima_f$mean)
)
```
Looking at the plot, it is clear that both models produce similar and fairly accurate predictions.
## Creating collections of time series
In the previous sections we have seen how to display a time series and forecasts for its future values. However, the main goal of the **vctsfr** package is to facilitate the visualization of collections of time series so that you can visually compare forecasts for their future values.
In this section we study how to build these collections.
For this purpose, the **vctsfr** package provides three functions:
* `ts_info()` allows you to create an object with information about a time series.
* `prediction_info()` allows you to create an object with information about a forecast.
* `pi_info()` allows you to create an object with information about the prediction interval associated with a forecast.
A collection of time series is a list of objects created with (returned by) the `ts_info()` function. Let's first create a collection storing the historical values of two time series:
```{r}
collection1 <- list(ts_info(USAccDeaths), ts_info(UKDriverDeaths))
```
In the next section we will use the collections built in this section to visualize their information. Next, we use a dataset included in the **Mcomp** package to create another collection of series. The **Mcomp** package contains datasets of forecasting competitions. We are going to create a collection of 18 quarterly time series, with their associated next 12 future values and forecasts for their future values (using the previously applied `ets()` function of the **forecast** package).
```{r}
library(Mcomp)
# select the industry, quarterly series from M1 competition (18 series)
M1_quarterly <- subset(M1, 4, "industry")
# build the collection
collection2 <- vector("list", length = length(M1_quarterly))
for (ind in seq_along(M1_quarterly)) {
timeS <- M1_quarterly[[ind]]$x # time series
name <- M1_quarterly[[ind]]$st # time series's name
fut <- M1_quarterly[[ind]]$xx # future values
ets_fit <- ets(timeS) # ES fit
ets_for <- forecast(ets_fit, h = length(fut)) # ES forecast
collection2[[ind]] <- ts_info(timeS,
prediction_info("ets", ets_for$mean),
future = fut,
name = name
)
}
```
Finally, we use the same dataset of 18 time series to create a collection of time series, with two forecasts (obtained with two different forecasting models) for each series and some prediction intervals associated with each forecast.
```{r}
collection3 <- vector("list", length = length(M1_quarterly))
for (ind in seq_along(M1_quarterly)) {
t <- M1_quarterly[[ind]]$x # time series
name <- M1_quarterly[[ind]]$st # time series's name
f <- M1_quarterly[[ind]]$xx # "future" values
ets_fit <- ets(t) # ES fit
ets_f <- forecast(ets_fit, h = length(f), level = 90) # ES forecast
arima_fit <- auto.arima(t) # ARIMA fit
arima_f <- forecast(arima_fit, h = length(f), # ARIMA forecast
level = c(80, 90)
)
collection3[[ind]] <- ts_info(t,
future = f,
prediction_info("ets",
ets_f$mean,
pi_info(90,
ets_f$lower,
ets_f$upper)
),
prediction_info("arima",
arima_f$mean,
pi_info(80,
arima_f$lower[, 1],
arima_f$upper[, 1]
),
pi_info(90,
arima_f$lower[, 2],
arima_f$upper[, 2]
)
),
name = name)
}
```
It can be noted that the exponential smoothing forecasts have a prediction interval, while the ARIMA forecasts have two prediction intervals. Although it does not happen in these examples, different time series in a collection can include forecasts done with different models.
## Visualizing a time series from a collection
Once you have created a collection, you can see the information about one of its series with the `plot_collection()` function. The basic way of using this function is specifying a collection and the number (index) of the series in the collection. Let's see an example using a collection built in the previous section:
```{r}
plot_collection(collection3, number = 3)
```
`plot_collection()` has displayed all available information about the series with index 3, except for the prediction intervals. You can choose to display a subset of the forecasts associated with a time series providing a vector with the names of the forecasting methods you want to select:
```{r}
plot_collection(collection3, number = 3, methods = "ets")
```
Finally, if you display the forecasts of just one forecasting method and this method has prediction intervals, you can display one of its prediction intervals providing its level:
```{r}
plot_collection(collection3, number = 3, methods = "arima", level = 90)
```
Looking at the plot, all predicted future values fall within the prediction interval.
## The web-based GUI for visualizing collections of time series
Although the `plot_collection()` function is handy, the best way of navigating through the different series of a collection is to use the `GUI_collection()` function, which launches a Shiny GUI in a web browser.
```{r, eval=FALSE}
GUI_collection(collection3)
```
This is how the GUI looks like:
{width="90%"}
Using the GUI the user can select:
* Which time series to display.
* If the data points are highlighted.
* Which forecasting methods to display.
* In the case that only one forecast is displayed and this forecast has prediction intervals, which prediction interval to show.
Apart from the time series, the GUI shows information about the forecast accuracy of the displayed forecasting methods. Currently, for each forecasting method the following forecasting accuracy measures are computed:
* RMSE: root mean squared error
* MAPE: mean absolute percentage error
* MAE: mean absolute error
* ME: mean error
* MPE: mean percentage error.
* sMAPE: symmetric MAPE
* MASE: mean absolute scaled error
This way, you can compare the displayed forecasting methods both visually and through forecast accuracy measures.
Next, we describe how the forecasting accuracy measures are computed for a forecasting horizon $h$ ($y_t$ and $\hat{y}_t$ are the actual future value and its forecast for horizon $t$ respectively):
$$
RMSE = \sqrt{\frac{1}{h}\sum_{t=1}^{h} (y_t-\hat{y}_t)^2}
$$
$$
MAPE = \frac{1}{h}\sum_{t=1}^{h} 100\frac{|y_t-\hat{y}_t|}{y_t}
$$
$$
MAE = \frac{1}{h}\sum_{t=1}^{h} |y_t-\hat{y}_t|
$$
$$
ME = \frac{1}{h}\sum_{t=1}^{h} y_t-\hat{y}_t
$$
$$
MPE = \frac{1}{h}\sum_{t=1}^{h} 100\frac{y_t-\hat{y}_t}{y_t}
$$
$$
sMAPE = \frac{1}{h}\sum_{t=1}^{h} 200\frac{\left|y_{t}-\hat{y}_{t}\right|}{|y_t|+|\hat{y}_t|}
$$
$$
MASE = \frac{\frac{1}{h}\sum_{t=1}^{h} |y_t - \hat{y}_t|}{\frac{1}{T-f}\sum_{t=f+1}^{T} |h_t - h_{t-f}|}
$$
In the MASE computation $T$ is the length of the training set (i.e., the length of the time series with historical values), $h_t$ is the t-th historical value and $f$ is the frequency of the time series (1 for annual data, 4 for quarterly data, 12 for monthly data, ...).
|
/scratch/gouwar.j/cran-all/cranData/vctsfr/inst/doc/vctsfr.Rmd
|
---
title: "vctsfr"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{vctsfr}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r, include = FALSE}
knitr::opts_chunk$set(
fig.width = 6,
fig.heigth = 2,
collapse = TRUE,
comment = "#>"
)
```
In this document we present the **vctsfr** package, which can be an useful tool for those involved in time series forecasting because it allows you to visually compare the predictions of several forecasting models. The **vctsfr** package is especially convenient when you want to visually compare the predictions of several forecasting methods across a collection of time series.
The **vctsfr** package makes it easy the visualization of collections of time series and, optionally, their future values and forecasts for those future values. The forecasts can include prediction intervals. This package is particularly useful when you have forecasts (maybe from different models) for several time series and you want to display them in order to compare their results.
This package arises from a need of her authors. Frequently, we used several forecasting methods to predict the future values of collections of time series (typically belonging to time series competitions). The usual way of comparing the performance of the forecasting methods is to compute a global measure of forecast accuracy for every method based on all its forecasts for all the series of the competition. However, we miss a way of visually compare the performance of different methods over a particular series. This package fills this gap.
This package also facilitates the visualization of just a collection of time series (without forecasts).
## Visualizing a single time series
If you only want to display a single time series and, optionally, information about its future values and/or a forecast for its future values you can use the `plot_ts()` function. Let us see how it works.
```{r}
library(vctsfr)
plot_ts(USAccDeaths) # plotting a time series
```
By default, `plot_ts()` shows the data points in the time series. However, you can omit them with the `sdp` parameter:
```{r}
plot_ts(USAccDeaths, sdp = FALSE)
```
Let us now display the same time series and a forecast for its next 12 months using the exponential smoothing model implemented in the **forecast** package (`ets()` function):
```{r}
library(forecast)
ets_fit <- ets(USAccDeaths)
ets_f <- forecast(ets_fit, h = 12)
plot_ts(USAccDeaths, prediction = ets_f$mean, method = "ets")
```
If the forecasting method computes prediction intervals, they can be displayed. For example, let's add a 90% prediction interval to the previous forecast:
```{r}
library(forecast)
ets_fit <- ets(USAccDeaths)
ets_f <- forecast(ets_fit, h = 12, level = 90)
plot_ts(USAccDeaths,
prediction = ets_f$mean,
method = "ets",
lpi = ets_f$lower,
upi = ets_f$upper,
level = 90
)
```
Finally, the actual values that are predicted can also be displayed:
```{r}
timeS <- window(USAccDeaths, end = c(1977, 12))
fut <- window(USAccDeaths, start = c(1978, 1))
ets_fit <- ets(timeS)
ets_f <- forecast(ets_fit, h = length(fut), level = 80)
plot_ts(timeS,
future = fut,
prediction = ets_f$mean,
method = "ets",
lpi = ets_f$lower,
upi = ets_f$upper,
level = 80
)
```
Summarizing, the `plot_ts()` function is useful to visualize a time series and, optionally, a forecast for its future values.
In all the functions of the **vctsfr** package the time series parameter, i.e. the historical values of the series, is specified as an object of class `ts`. The future values, forecasts and prediction intervals can be specified as a numeric vector or as an object of class `ts`.
## Visualizing several forecasts
When you want to compare several forecasts for the future values of a time series you can use the function `plot_predictions()`. The forecasts are passed to the function as a list, each component of the list is a forecast and the name of the component is the name of the forecasting method. Let us see an example in which, given a time series, the forecasts for its future values, using the ARIMA and exponential smoothing models implemented in the **forecast** package, are displayed:
```{r}
timeS <- window(USAccDeaths, end = c(1977, 12)) # historical values
fut <- window(USAccDeaths, start = c(1978, 1)) # "future" values
ets_fit <- ets(timeS) # exponential smoothing fit
ets_f <- forecast(ets_fit, h = length(fut)) # exponential smoothing forecast
arima_fit <- auto.arima(timeS) # ARIMA fit
arima_f <- forecast(arima_fit, h = length(fut)) # ARIMA forecast
plot_predictions(timeS, future = fut,
predictions = list(ets = ets_f$mean, arima = arima_f$mean)
)
```
Looking at the plot, it is clear that both models produce similar and fairly accurate predictions.
## Creating collections of time series
In the previous sections we have seen how to display a time series and forecasts for its future values. However, the main goal of the **vctsfr** package is to facilitate the visualization of collections of time series so that you can visually compare forecasts for their future values.
In this section we study how to build these collections.
For this purpose, the **vctsfr** package provides three functions:
* `ts_info()` allows you to create an object with information about a time series.
* `prediction_info()` allows you to create an object with information about a forecast.
* `pi_info()` allows you to create an object with information about the prediction interval associated with a forecast.
A collection of time series is a list of objects created with (returned by) the `ts_info()` function. Let's first create a collection storing the historical values of two time series:
```{r}
collection1 <- list(ts_info(USAccDeaths), ts_info(UKDriverDeaths))
```
In the next section we will use the collections built in this section to visualize their information. Next, we use a dataset included in the **Mcomp** package to create another collection of series. The **Mcomp** package contains datasets of forecasting competitions. We are going to create a collection of 18 quarterly time series, with their associated next 12 future values and forecasts for their future values (using the previously applied `ets()` function of the **forecast** package).
```{r}
library(Mcomp)
# select the industry, quarterly series from M1 competition (18 series)
M1_quarterly <- subset(M1, 4, "industry")
# build the collection
collection2 <- vector("list", length = length(M1_quarterly))
for (ind in seq_along(M1_quarterly)) {
timeS <- M1_quarterly[[ind]]$x # time series
name <- M1_quarterly[[ind]]$st # time series's name
fut <- M1_quarterly[[ind]]$xx # future values
ets_fit <- ets(timeS) # ES fit
ets_for <- forecast(ets_fit, h = length(fut)) # ES forecast
collection2[[ind]] <- ts_info(timeS,
prediction_info("ets", ets_for$mean),
future = fut,
name = name
)
}
```
Finally, we use the same dataset of 18 time series to create a collection of time series, with two forecasts (obtained with two different forecasting models) for each series and some prediction intervals associated with each forecast.
```{r}
collection3 <- vector("list", length = length(M1_quarterly))
for (ind in seq_along(M1_quarterly)) {
t <- M1_quarterly[[ind]]$x # time series
name <- M1_quarterly[[ind]]$st # time series's name
f <- M1_quarterly[[ind]]$xx # "future" values
ets_fit <- ets(t) # ES fit
ets_f <- forecast(ets_fit, h = length(f), level = 90) # ES forecast
arima_fit <- auto.arima(t) # ARIMA fit
arima_f <- forecast(arima_fit, h = length(f), # ARIMA forecast
level = c(80, 90)
)
collection3[[ind]] <- ts_info(t,
future = f,
prediction_info("ets",
ets_f$mean,
pi_info(90,
ets_f$lower,
ets_f$upper)
),
prediction_info("arima",
arima_f$mean,
pi_info(80,
arima_f$lower[, 1],
arima_f$upper[, 1]
),
pi_info(90,
arima_f$lower[, 2],
arima_f$upper[, 2]
)
),
name = name)
}
```
It can be noted that the exponential smoothing forecasts have a prediction interval, while the ARIMA forecasts have two prediction intervals. Although it does not happen in these examples, different time series in a collection can include forecasts done with different models.
## Visualizing a time series from a collection
Once you have created a collection, you can see the information about one of its series with the `plot_collection()` function. The basic way of using this function is specifying a collection and the number (index) of the series in the collection. Let's see an example using a collection built in the previous section:
```{r}
plot_collection(collection3, number = 3)
```
`plot_collection()` has displayed all available information about the series with index 3, except for the prediction intervals. You can choose to display a subset of the forecasts associated with a time series providing a vector with the names of the forecasting methods you want to select:
```{r}
plot_collection(collection3, number = 3, methods = "ets")
```
Finally, if you display the forecasts of just one forecasting method and this method has prediction intervals, you can display one of its prediction intervals providing its level:
```{r}
plot_collection(collection3, number = 3, methods = "arima", level = 90)
```
Looking at the plot, all predicted future values fall within the prediction interval.
## The web-based GUI for visualizing collections of time series
Although the `plot_collection()` function is handy, the best way of navigating through the different series of a collection is to use the `GUI_collection()` function, which launches a Shiny GUI in a web browser.
```{r, eval=FALSE}
GUI_collection(collection3)
```
This is how the GUI looks like:
{width="90%"}
Using the GUI the user can select:
* Which time series to display.
* If the data points are highlighted.
* Which forecasting methods to display.
* In the case that only one forecast is displayed and this forecast has prediction intervals, which prediction interval to show.
Apart from the time series, the GUI shows information about the forecast accuracy of the displayed forecasting methods. Currently, for each forecasting method the following forecasting accuracy measures are computed:
* RMSE: root mean squared error
* MAPE: mean absolute percentage error
* MAE: mean absolute error
* ME: mean error
* MPE: mean percentage error.
* sMAPE: symmetric MAPE
* MASE: mean absolute scaled error
This way, you can compare the displayed forecasting methods both visually and through forecast accuracy measures.
Next, we describe how the forecasting accuracy measures are computed for a forecasting horizon $h$ ($y_t$ and $\hat{y}_t$ are the actual future value and its forecast for horizon $t$ respectively):
$$
RMSE = \sqrt{\frac{1}{h}\sum_{t=1}^{h} (y_t-\hat{y}_t)^2}
$$
$$
MAPE = \frac{1}{h}\sum_{t=1}^{h} 100\frac{|y_t-\hat{y}_t|}{y_t}
$$
$$
MAE = \frac{1}{h}\sum_{t=1}^{h} |y_t-\hat{y}_t|
$$
$$
ME = \frac{1}{h}\sum_{t=1}^{h} y_t-\hat{y}_t
$$
$$
MPE = \frac{1}{h}\sum_{t=1}^{h} 100\frac{y_t-\hat{y}_t}{y_t}
$$
$$
sMAPE = \frac{1}{h}\sum_{t=1}^{h} 200\frac{\left|y_{t}-\hat{y}_{t}\right|}{|y_t|+|\hat{y}_t|}
$$
$$
MASE = \frac{\frac{1}{h}\sum_{t=1}^{h} |y_t - \hat{y}_t|}{\frac{1}{T-f}\sum_{t=f+1}^{T} |h_t - h_{t-f}|}
$$
In the MASE computation $T$ is the length of the training set (i.e., the length of the time series with historical values), $h_t$ is the t-th historical value and $f$ is the frequency of the time series (1 for annual data, 4 for quarterly data, 12 for monthly data, ...).
|
/scratch/gouwar.j/cran-all/cranData/vctsfr/vignettes/vctsfr.Rmd
|
#' Tropheus IK coord dataset
#'
#' A data frame of 511 observations of 58 variables.
#' This is a subset of the Tropheus data frame constituted by cichlid fishes
#' of the species \emph{Tropheus moorii} (color morph 'Kaiser')
#' collected from six locations of Lake Tanganyika (Kerschbaumer et al., 2013, 2014).
#' The coordinates result from the generalised Procrustes analysis, for this subset,
#' of the 2D Cartesian coordinates of 19 landmarks quantifying the external body morphology of adult fishes.
#'
#' \itemize{
#' \item \strong{List_TropheusData_ID} {Specimen ID}
#' \item \strong{Extractionnr.} {Extraction number for genomic DNA}
#' \item \strong{G} {Group number}
#' \item \strong{POP.ID} {Population Id}
#' \item \strong{Sex} {Sex}
#' \item \strong{Allo.Symp} {Allopatric or sympatric population}
#' \item \strong{X1 ... Y19} {Procrustes coordinates of 19 landmarks}
#' \item \strong{Pzep3_1 ... UME003_2} {Genotype for 6 microsatellite markers}
#' }
#'
#' @seealso \code{\link{Tropheus}}
#'
#' @references Kerschbaumer M, Mitteroecker P, Sturmbauer C (2014)
#' Evolution of body shape in sympatric versus non-sympatric Tropheus populations of Lake Tanganyika. \emph{Heredity 112(2)}: 89–98. \url{https://doi.org/10.1038/hdy.2013.78}
#' @references Kerschbaumer M, Mitteroecker P, Sturmbauer C (2013)
#' Data from: Evolution of body shape in sympatric versus non-sympatric Tropheus populations of Lake Tanganyika. \emph{Dryad Digital Repository}. \url{https://doi.org/10.5061/dryad.fc02f}
#'
#' @name Tropheus.IK.coord
#' @usage data(Tropheus.IK.coord)
#' @format A data frame with 511 rows and 58 variables
#' @docType data
NULL
|
/scratch/gouwar.j/cran-all/cranData/vcvComp/R/Tropheus-IK-coord-dataset.R
|
#' Tropheus dataset
#'
#' A data frame of 723 observations of 57 variables extracted from a freely available dataset,
#' downloaded from the Dryad digital repository (\url{https://doi.org/10.5061/dryad.fc02f}).
#' The observations correspond to cichlid fishes of the species \emph{Tropheus moorii}
#' (color morphs 'Kaiser' and 'Kirschfleck') and \emph{T. polli} collected from eight locations
#' of Lake Tanganyika (Kerschbaumer et al., 2014).
#' The main numerical variables provided are the 2D Cartesian coordinates of 19 landmarks
#' quantifying the external body morphology of adult fishes
#' and the genotypes for 6 microsatellite markers.
#'
#' \itemize{
#' \item \strong{List_TropheusData_ID} {Specimen ID}
#' \item \strong{Extractionnr.} {Extraction number for genomic DNA}
#' \item \strong{G} {Group number}
#' \item \strong{POP.ID} {Population Id}
#' \item \strong{Sex} {Sex}
#' \item \strong{Allo.Symp} {Allopatric or sympatric population}
#' \item \strong{X1 ... Y19} {Cartesian coordinates of 19 landmarks}
#' \item \strong{Pzep3_1 ... UME003_2} {Genotype for 6 microsatellite markers}
#' }
#'
#' @references Kerschbaumer M, Mitteroecker P, Sturmbauer C (2014)
#' Evolution of body shape in sympatric versus non-sympatric Tropheus populations of Lake Tanganyika. \emph{Heredity 112(2)}: 89–98. \url{https://doi.org/10.1038/hdy.2013.78}
#' @references Kerschbaumer M, Mitteroecker P, Sturmbauer C (2013)
#' Data from: Evolution of body shape in sympatric versus non-sympatric Tropheus populations of Lake Tanganyika. \emph{Dryad Digital Repository}. \url{https://doi.org/10.5061/dryad.fc02f}
#'
#' @name Tropheus
#' @usage data(Tropheus)
#' @format A data frame with 723 rows and 57 variables
#' @docType data
NULL
|
/scratch/gouwar.j/cran-all/cranData/vcvComp/R/Tropheus-dataset.R
|
#' Between-group covariance matrix
#'
#' @description Computes the between-group covariance matrix.
#' The effect of sexual dimorphism can be removed by using, for each group,
#' the average of the mean of males and the mean of females.
#'
#' @param X a data matrix with variables in columns and group names as row names
#' @param groups a character / factor vector containing grouping variable
#' @param sex NULL (default). A character / factor vector containing sex variable,
#' to remove sexual dimorphism by averaging males and females in each group
#' @param center either a logical value or a numeric vector of length equal to the number of columns of X
#' @param weighted logical. Should the between-group covariance matrix be weighted?
#'
#' @return The between-group covariance matrix
#'
#' @importFrom stats cov cov.wt
#'
#' @seealso \code{\link[stats:cor]{cov}}, \code{\link[stats]{cov.wt}}
#'
#' @examples
#'
#' # Data matrix of 2D landmark coordinates
#' data("Tropheus.IK.coord")
#' coords <- which(names(Tropheus.IK.coord) == "X1"):which(names(Tropheus.IK.coord) == "Y19")
#' proc.coord <- as.matrix(Tropheus.IK.coord[coords])
#'
#' # Between-group covariance matrix for all populations
#' B <- cov.B(proc.coord, groups = Tropheus.IK.coord$POP.ID)
#'
#' # Between-group covariance matrix for all populations, pooled by sex
#' B.mf <- cov.B(proc.coord, groups = Tropheus.IK.coord$POP.ID, sex = Tropheus.IK.coord$Sex)
#'
#' @export
cov.B <-
function (X, groups, sex = NULL, center = FALSE, weighted = FALSE) {
if (is.data.frame(X))
X <- as.matrix(X)
else if (!is.matrix(X))
stop("'X' must be a matrix or a data frame")
if (!all(is.finite(X)))
stop("'X' must contain finite values only")
# Groups
groups <- factor(groups)
glev <- levels(groups)
nlev <- length(glev)
gsizes <- as.vector(table(groups))
if (1 %in% gsizes) {
warning("group with one entry found")
}
# Sex
slev <- 0
if (!is.null(sex)) {
sex <- factor(sex)
slev <- levels(sex)
if (length(slev) != 2) {
warning("The number of sex categories is different from two.
Sexual dimorphism will not be removed.")
}
}
p <- ncol(X)
Gmeans <- matrix(NA, nrow = nlev, ncol = p, dimnames = list(glev, colnames(X)))
for (i in 1:nlev) {
# No correction for sexual dimorphism
if (is.null(sex) || length(slev) != 2) {
Gmeans[i, ] <- apply(X[which(groups == glev[i]), ], 2, mean)
}
# Correction for sexual dimorphism: mean males / females
if (!is.null(sex) & length(slev) == 2) {
Gsex1 <- apply(X[which(groups == glev[i] & sex == slev[1]), ], 2, mean)
Gsex2 <- apply(X[which(groups == glev[i] & sex == slev[2]), ], 2, mean)
Gsex <- rbind(Gsex1, Gsex2)
Gmeans[i, ] <- apply(Gsex, 2, mean)
}
}
if (weighted == TRUE) {
wt <- gsizes / sum(gsizes)
wcov <- cov.wt(Gmeans, wt, cor = FALSE, center)
B <- wcov$cov
}
if (weighted == FALSE) {
B <- cov(Gmeans)
}
dimnames(B) <- list(colnames(X), colnames(X))
return(B)
}
|
/scratch/gouwar.j/cran-all/cranData/vcvComp/R/cov.B.R
|
#' Within-group covariance matrix
#'
#' @description Computes the pooled within-group covariance matrix.
#' The effect of sexual dimorphism can be removed by using, for each group,
#' the average of the covariance matrix of males and the covariance matrix of females.
#'
#' @param X a data matrix with variables in columns and group names as row names
#' @param groups a character / factor vector containing grouping variable
#' @param sex NULL (default). A character / factor vector containing sex variable,
#' to remove sexual dimorphism by averaging males and females in each group
#' @param weighted logical. If FALSE (default), the average of all the within-group covariance matrices is used.
#' If TRUE, the within-group covariance matrices are weighted by their sample size.
#'
#' @return The pooled within-group covariance matrix
#'
#' @importFrom stats cov
#'
#' @seealso \code{\link[stats:cor]{cov}}
#'
#' @examples
#'
#' # Data matrix of 2D landmark coordinates
#' data("Tropheus.IK.coord")
#' coords <- which(names(Tropheus.IK.coord) == "X1"):which(names(Tropheus.IK.coord) == "Y19")
#' proc.coord <- as.matrix(Tropheus.IK.coord[coords])
#'
#' # Pooled within-group covariance matrix for all populations (weighted by sample size)
#' W <- cov.W(proc.coord, groups = Tropheus.IK.coord$POP.ID, weighted = TRUE)
#'
#' # Pooled within-group covariance matrix for all populations (unweighted)
#' W <- cov.W(proc.coord, groups = Tropheus.IK.coord$POP.ID)
#'
#' # Within-group covariance matrix for all populations, pooled by sex
#' W.mf <- cov.W(proc.coord, groups = Tropheus.IK.coord$POP.ID, sex = Tropheus.IK.coord$Sex)
#'
#' @export
cov.W <-
function (X, groups, sex = NULL, weighted = FALSE) {
if (is.data.frame(X))
X <- as.matrix(X)
else if (!is.matrix(X))
stop("'X' must be a matrix or a data frame")
if (!all(is.finite(X)))
stop("'X' must contain finite values only")
# Groups
groups <- factor(groups)
glev <- levels(groups)
nlev <- length(glev)
gsizes <- as.vector(table(groups))
if (1 %in% gsizes) {
warning("group with one entry found")
}
# Weighting
wt <- gsizes
if (weighted == FALSE) {
wt <- rep(2, nlev)
}
# Sex
slev <- 0
if (!is.null(sex)) {
sex <- factor(sex)
slev <- levels(sex)
if (length(slev) != 2) {
warning("The number of sex categories is different from two.
Sexual dimorphism will not be removed.")
}
}
p <- ncol(X) # number of variables
Gvcv <- array(NA, dim = c(p, p, nlev))
for (i in 1:nlev) {
# No correction for sexual dimorphism
if (is.null(sex) || length(slev) != 2) {
Xi <- X[which(groups == glev[i]), ]
Gvcv[, , i] <- cov(Xi) * (wt[i] - 1)
}
# Correction for sexual dimorphism: mean males / females
if (!is.null(sex) & length(slev) == 2) {
X1 <- X[which(groups == glev[i] & sex == slev[1]), ]
X2 <- X[which(groups == glev[i] & sex == slev[2]), ]
Gsex <- array(c(cov(X1), cov(X2)), dim = c(p, p, 2))
Gvcv[, , i] <- apply(Gsex, c(1, 2), mean) * (wt[i] - 1)
}
}
dimnames(Gvcv) <- list(colnames(p), colnames(p), glev)
W <- apply(Gvcv, c(1, 2), sum)
W <- W / (sum(wt) - nlev)
return(W)
}
|
/scratch/gouwar.j/cran-all/cranData/vcvComp/R/cov.W.R
|
#' Group covariance matrices
#'
#' @description Computes the covariance matrix of each group.
#' The effect of sexual dimorphism can be removed by using, for each group,
#' the average of the covariance matrix of males and the covariance matrix of females.
#'
#' @param X a data matrix with variables in columns and group names as row names
#' @param groups a character / factor vector containing grouping variable
#' @param sex NULL (default). A character / factor vector containing sex variable,
#' to remove sexual dimorphism by averaging males and females in each group
#' @param use an optional character string giving a method for computing covariances in the presence of missing values.
#' This must be (an abbreviation of) one of the strings "everything", "all.obs", "complete.obs", "na.or.complete", or "pairwise.complete.obs".
#'
#' @return A (p x p x m) array of covariance matrices,
#' where p is the number of variables and m the number of groups.
#'
#' @importFrom stats cov
#'
#' @seealso \code{\link[stats:cor]{cov}} and \code{\link[base]{scale}}
#'
#' @examples
#'
#' # Data matrix of 2D landmark coordinates
#' data("Tropheus.IK.coord")
#' coords <- which(names(Tropheus.IK.coord) == "X1"):which(names(Tropheus.IK.coord) == "Y19")
#' proc.coord <- as.matrix(Tropheus.IK.coord[coords])
#'
#' # Covariance matrix of each population
#' S.phen.pop <- cov.group(proc.coord, groups = Tropheus.IK.coord$POP.ID)
#'
#' # Covariance matrix of each population, pooled by sex
#' S.phen.pooled <- cov.group(proc.coord,
#' groups = Tropheus.IK.coord$POP.ID, sex = Tropheus.IK.coord$Sex)
#'
#' @export
cov.group <-
function (X, groups, sex = NULL, use = "everything") {
if (is.data.frame(X))
X <- as.matrix(X)
else if (!is.matrix(X))
stop("'X' must be a matrix or a data frame")
if (!all(is.finite(X)))
stop("'X' must contain finite values only")
# Groups
groups <- factor(groups)
glev <- levels(groups)
nlev <- length(glev)
gsizes <- as.vector(table(groups))
if (1 %in% gsizes) {
warning("group with one entry found")
}
# Sex
slev <- 0
if (!is.null(sex)) {
sex <- factor(sex)
slev <- levels(sex)
if (length(slev) != 2) {
warning("The number of sex categories is different from two.
Sexual dimorphism will not be removed.")
}
}
p <- ncol(X) # number of variables
Gvcv <- array(NA, dim = c(p, p, nlev))
for (i in 1:nlev) {
# No correction for sexual dimorphism
if (is.null(sex) || length(slev) != 2) {
Xi <- X[which(groups == glev[i]), ]
Gvcv[, , i] <- cov(Xi, use = use)
}
# Correction for sexual dimorphism: mean males / females
if (!is.null(sex) & length(slev) == 2) {
X1 <- X[which(groups == glev[i] & sex == slev[1]), ]
X2 <- X[which(groups == glev[i] & sex == slev[2]), ]
Gsex <- array(c(cov(X1, use = use), cov(X2, use = use)), dim = c(p, p, 2))
Gvcv[, , i] <- apply(Gsex, c(1, 2), mean)
}
}
dimnames(Gvcv) <- list(colnames(X), colnames(X), glev)
return(Gvcv)
}
|
/scratch/gouwar.j/cran-all/cranData/vcvComp/R/cov.group.R
|
#' Difference test for successive relative eigenvalues
#'
#' @description Tests the difference between two successive relative eigenvalues
#'
#' @param n the sample size(s), given as a number or a vector of length 2
#' @param relValues a vector of relative eigenvalues
#'
#' @return The P-values for the test of difference between successive eigenvalues
#'
#' @seealso \code{\link{relative.eigen}} for the computation of relative eigenvalues,
#' @seealso \code{\link[stats:Chisquare]{pchisq}} for Chi-squared distribution
#'
#' @references Mardia KV, Kent JT, Bibby JM (1979)
#' \emph{Multivariate analysis}. Academic Press, London.
#'
#' @examples
#'
#' # Data matrix of 2D landmark coordinates
#' data("Tropheus.IK.coord")
#' coords <- which(names(Tropheus.IK.coord) == "X1"):which(names(Tropheus.IK.coord) == "Y19")
#' proc.coord <- as.matrix(Tropheus.IK.coord[coords])
#'
#' # Data reduction
#' phen.pca <- prcomp(proc.coord, rank. = 5, tol = sqrt(.Machine$double.eps))
#' pc.scores <- phen.pca$x
#'
#' # Covariance matrix of each population
#' S.phen.pop <- cov.group(pc.scores, groups = Tropheus.IK.coord$POP.ID)
#'
#' # Relative PCA = relative eigenanalysis between 2 covariance matrices
#' # (population IKA1 relative to IKS5)
#' relEigen.a1s5 <- relative.eigen(S.phen.pop[, , "IKA1"], S.phen.pop[, , "IKS5"])
#'
#' # Test of the difference between 2 successives eigenvalues
#' # of the covariance matrix of IKA1 relative to IKS5
#' n_ika1 <- length(which(Tropheus.IK.coord$POP.ID == "IKA1")) # sample size for IKA1
#' n_iks5 <- length(which(Tropheus.IK.coord$POP.ID == "IKS5")) # sample size for IKS5
#' eigen.test(n = c(n_ika1, n_iks5), relValues = relEigen.a1s5$relValues)
#'
#' @export
eigen.test <-
function (n, relValues) {
if (is.null(n))
stop("supply the sample size 'n'")
if (!is.vector(n) | !is.numeric(n))
stop("supply the sample size 'n' as a number or a numeric vector")
if (length(n) < 1 | length(n) > 2)
stop("supply the sample size 'n' as a single number or a vector of length 2")
if (length(n) == 2)
n <- 2 / (1 / n[1] + 1 / n[2]) # harmonic mean
if (!is.vector(relValues) | !is.numeric(relValues))
stop("supply the relative eigenvalues 'relValues' as a numeric vector")
if (length(relValues) < 2)
stop("supply at least 2 numbers in 'relValues'")
p <- length(relValues) # number of relative eigenvalues
pValues <- rep(1, (p - 1))
for (i in 1:(p - 1)) {
val <- 2 * n * log((relValues[i] + relValues[i + 1]) / (2 * (relValues[i] * relValues[i + 1]) ^ 0.5))
pValues[i] <- pchisq(q = val, df = 2, lower.tail = FALSE)
}
return(pValues)
}
|
/scratch/gouwar.j/cran-all/cranData/vcvComp/R/eigen.test.R
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.