native: 0 functions analysed · 0 typed · 0 untypeable · 0 timed out · 2 entry points (0 typed) · R: 227 definitions, 17 typed strict, 149 gradual, prelude debt 145 · fuzzing: 13 definitions, 0 unsound, 8 accept calls outside their domain · tyr dc7f1a7 · Rsem 7bcb45f · NativeSem 770a1eb · rstt 2b2696f unpinned
unbound variable on a native symbol tyr could not bind — the native panel’s loss, arriving here.NULLdplyr::group_vars — a name the prelude does not declarename: dplyr::group_vars
reconstruct_tibble <- function(input, output, ungrouped_vars = character()) {
if (inherits(input, "grouped_df")) {
old_groups <- dplyr::group_vars(input)
new_groups <- intersect(setdiff(old_groups, ungrouped_vars), names(output))
dplyr::grouped_df(
output,
new_groups,
drop = dplyr::group_by_drop_default(input)
)
} else if (inherits(input, "tbl_df")) {
# Assume name repair carried out elsewhere
as_tibble(output, .name_repair = "minimal")
} else {
output
}
}argument: @(INT1<> | null) failing call: base::seq_len(NULL)
seq_nrow <- function(x) seq_len(nrow(x))argument: @(INT1<> | null) failing call: base::seq_len(NULL)
seq_ncol <- function(x) seq_len(ncol(x))(((x: <@"[[", ...>) -> any) & ((x: v('I573)<~@"[[", ...>) -> v1('I573)<>) & ((x: { 'I561 }<~@"[[", ...>) -> 'I561))<>| parameter | change | call | returned |
|---|---|---|---|
| x | kind:lang | last("x" = quote(f(x))) | sym |
| x | kind:lang | last(quote(f(x))) | sym |
| x | kind:null | last("x" = NULL) | null |
| call | verdict | error |
|---|---|---|
| last("x" = list()) | error_type | base::[[: attempt to select less than one element in integerOneIndex |
| last(list()) | error_type | base::[[: attempt to select less than one element in integerOneIndex |
| last(numeric(0)) | error_type | base::[[: attempt to select less than one element in integerOneIndex |
last <- function(x) x[[length(x)]]make.unique — a name the prelude does not declarename: make.unique
tidyr_legacy <- function(nms, prefix = "V", sep = "") {
if (length(nms) == 0) {
return(character())
}
blank <- nms == ""
nms[!blank] <- make.unique(nms[!blank], sep = sep)
new_nms <- setdiff(paste(prefix, seq_along(nms), sep = sep), nms)
nms[blank] <- new_nms[seq_len(sum(blank))]
nms
}Failure("Unsupported argument after an ellipsis.")check_data_frame <- function(x, ..., arg = caller_arg(x), call = caller_env()) {
if (!is.data.frame(x)) {
cli::cli_abort(
"{.arg {arg}} must be a data frame, not {.obj_type_friendly {x}}.",
...,
call = call
)
}
}is_list — a name the prelude does not declarename: is_list
tidyr_new_list <- function(x) {
if (!is_list(x)) {
cli::cli_abort("`x` must be a list.", .internal = TRUE)
}
names <- names(x)
if (is.null(names)) {
attributes(x) <- NULL
} else {
attributes(x) <- list(names = names)
}
x
}check_data_frame — one of the package’s own names, itself untypedname: check_data_frame
tidyr_col_modify <- function(data, cols) {
# Implement from first principles to avoid edge cases in
# data frame methods for `[<-` and `[[<-`.
# Assume each element of `cols` has the correct size.
check_data_frame(data, .internal = TRUE)
if (!is_list(cols)) {
cli::cli_abort("`cols` must be a list.", .internal = TRUE)
}
size <- vec_size(data)
data <- tidyr_new_list(data)
names <- names(cols)
for (i in seq_along(cols)) {
name <- names[[i]]
data[[name]] <- cols[[i]]
}
# Assume that we can return a bare data frame that will up restored to
# a tibble / grouped df as needed elsewhere
data <- new_data_frame(data, n = size)
data
}check_dots_empty0 — a name the prelude does not declarename: check_dots_empty0
list_replace_null <- function(x, sizes, ..., ptype = NULL, size = 1L) {
check_dots_empty0(...)
if (!vec_is_list(x)) {
cli::cli_abort("`x` must be a list.", .internal = TRUE)
}
if (is_list_of(x)) {
cli::cli_abort(
"`x` can't be a list-of. Unclass first and provide `ptype`.",
.internal = TRUE
)
}
if (vec_any_missing(x)) {
null <- vec_detect_missing(x)
null <- which(null)
if (is_null(ptype)) {
replacement <- list(unspecified(size))
} else {
replacement <- list(vec_init(ptype, size))
}
x <- vec_assign(x, null, replacement)
if (size != 0L) {
sizes <- vec_assign(sizes, null, size)
}
}
list(x = x, sizes = sizes)
}check_dots_empty0 — a name the prelude does not declarename: check_dots_empty0
list_replace_empty_typed <- function(x, sizes, ..., ptype = NULL, size = 1L) {
check_dots_empty0(...)
if (!vec_is_list(x)) {
cli::cli_abort("`x` must be a list.", .internal = TRUE)
}
if (is_list_of(x)) {
cli::cli_abort("`x` can't be a list-of. Unclass first.", .internal = TRUE)
}
if (size == 0L) {
cli::cli_abort("`size` should never be 0.", .internal = TRUE)
}
empty <- sizes == 0L
if (any(empty)) {
empty <- which(empty)
if (is_null(ptype)) {
replacement <- map(vec_slice(x, empty), function(elt) vec_init(elt, size))
} else {
replacement <- list(vec_init(ptype, size))
}
x <- vec_assign(x, empty, replacement)
sizes <- vec_assign(sizes, empty, size)
}
list(x = x, sizes = sizes)
}vec_any_missing — a name the prelude does not declarename: vec_any_missing
list_all_vectors2 <- function(x) {
if (vec_any_missing(x)) {
missing <- vec_detect_missing(x)
x <- vec_slice(x, !missing)
}
list_all_vectors(x)
}vec_set_names — a name the prelude does not declarename: vec_set_names
list_of_ptype <- function(x) {
ptype <- attr(x, "ptype", exact = TRUE)
# ptypes should always be unnamed, but this isn't guaranteed right now.
# See https://github.com/r-lib/vctrs/pull/1020#discussion_r411327472
ptype <- vec_set_names(ptype, NULL)
ptype
}| parameter | change | call | returned |
|---|---|---|---|
| inner | drop | apply_names_sep(quote(f(x)), NULL) | (CHR & ~vec1)<> with { } |
| inner | drop | apply_names_sep(function(...) c(0L, -1L), NULL) | (CHR & ~vec1)<> with { } |
| call | verdict | error |
|---|---|---|
| apply_names_sep(quote(f(x)), as.name("x"), "names_sep" = function(...) list()) | error_type | base::paste0: cannot coerce type 'closure' to vector of type 'character' |
| apply_names_sep("outer" = function(...) as.name("x"), "inner" = as.name("x"), "names_sep" = function(...) function(...) as.name("x")) | error_type | base::paste0: cannot coerce type 'closure' to vector of type 'character' |
| apply_names_sep(local({ p <- unserialize(serialize(new("externalptr"), NULL)); attributes(p) <- NULL; p }), list(new.env(), quote(f(x))), as.name("x")) | error_type | base::paste0: cannot coerce type 'externalptr' to vector of type 'character' |
| apply_names_sep(logical(0), function(...) as.name("x"), new.env()) | error_type | base::paste0: environments cannot be coerced to other types |
| apply_names_sep(function(...) c(0L, -1L), as.name("x"), NULL) | error_type | base::paste0: cannot coerce type 'closure' to vector of type 'character' |
apply_names_sep <- function(outer, inner, names_sep) {
# Need to avoid `paste0()` recycling issue. Not using `vec_paste0()`
# because that is too slow to be applied to each element (#1427).
# `outer` and `names_sep` are required to be length 1,
# so we only need to check `inner`.
if (length(inner) == 0L) {
character()
} else {
paste0(outer, names_sep, inner)
}
}vec_recycle_common — a name the prelude does not declarename: vec_recycle_common
vec_paste0 <- function(...) {
# Use tidyverse recycling rules to avoid size zero recycling bugs
args <- vec_recycle_common(...)
exec(paste0, !!!args)
}caller_arg — a name the prelude does not declarename: caller_arg
check_unique_names <- function(x, arg = caller_arg(x), call = caller_env()) {
if (length(x) > 0L && !is_named(x)) {
cli::cli_abort("All elements of {.arg {arg}} must be named.", call = call)
}
if (vec_duplicate_any(names(x))) {
cli::cli_abort("The names of {.arg {arg}} must be unique.", call = call)
}
}caller_arg — a name the prelude does not declarename: caller_arg
check_list_of_ptypes <- function(
x,
names,
arg = caller_arg(x),
call = caller_env()
) {
if (is.null(x)) {
set_names(list(), character())
} else if (vec_is(x) && vec_is_empty(x)) {
rep_named(names, list(x))
} else if (vec_is_list(x)) {
check_unique_names(x, arg = arg, call = call)
# Silently drop user supplied names not found in the data
x[intersect(names(x), names)]
} else {
cli::cli_abort(
"{.arg {arg}} must be `NULL`, an empty ptype, or a named list of ptypes.",
call = call
)
}
}caller_arg — a name the prelude does not declarename: caller_arg
check_list_of_functions <- function(
x,
names,
arg = caller_arg(x),
call = caller_env()
) {
if (is.null(x)) {
x <- set_names(list(), character())
} else if (is.function(x) || is_formula(x)) {
x <- rep_named(names, list(x))
} else if (!vec_is_list(x)) {
cli::cli_abort(
"{.arg {arg}} must be `NULL`, a function, or a named list of functions.",
call = call
)
}
check_unique_names(x, arg = arg, call = call)
x_names <- names(x)
for (i in seq_along(x)) {
x[[i]] <- as_function(
x[[i]],
arg = glue("{arg}${x_names[[i]]}"),
call = call
)
}
# Silently drop user supplied names not found in the data
x <- x[intersect(x_names, names)]
x
}caller_arg — a name the prelude does not declarename: caller_arg
check_list_of_bool <- function(
x,
names,
arg = caller_arg(x),
call = caller_env()
) {
if (is_bool(x)) {
rep_named(names, x)
} else if (vec_is_list(x)) {
check_unique_names(x, arg = arg, call = call)
x[intersect(names(x), names)]
} else {
cli::cli_abort(
"{.arg {arg}} must be a list or a single `TRUE` or `FALSE`.",
call = call
)
}
}Failure("Unsupported argument after an ellipsis.")with_indexed_errors <- function(
expr,
message,
...,
.error_call = caller_env(),
.frame = caller_env()
) {
try_fetch(
expr,
purrr_error_indexed = function(cnd) {
message <- message(cnd)
abort(
message,
...,
call = .error_call,
parent = cnd$parent,
.frame = .frame
)
}
)
}(((x: dbl, default: 'default?) -> dbl1 | 'default) & ((x: int, default: 'default?) -> (DBL1<> | INT1) | 'default))<>| call | verdict | error |
|---|---|---|
| int_max("x" = as.raw(c(0, 255))) | error_type | base::max: invalid 'type' (raw) of argument |
| int_max(as.raw(c(255)), "default" = NA_complex_) | error_type | base::max: invalid 'type' (raw) of argument |
| int_max(as.raw(c(0)), "default" = as.raw(c(0))) | error_type | base::max: invalid 'type' (raw) of argument |
| int_max(as.raw(c(0)), "default" = as.name("x")) | error_type | base::max: invalid 'type' (raw) of argument |
int_max <- function(x, default = -Inf) {
if (length(x) == 0) {
default
} else {
max(x)
}
}File "Rsem/lang/PAst.ml", line 145, characters 25-31: Assertion failed
.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
)
}caller_env — a name the prelude does not declarename: caller_env
.rlang_stop_unexpected_typeof <- function(x, call = caller_env()) {
abort(
sprintf("Unexpected type <%s>.", typeof(x)),
call = call
)
}is_vector — a name the prelude does not declarename: is_vector
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)
}
}Failure("Unsupported positional argument after a named one.")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 <- class(x)[[1L]]
}
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)
}is.object — a name the prelude does not declarename: is.object
obj_type_oo <- function(x) {
if (!is.object(x)) {
return("bare")
}
class <- inherits(x, c("R6", "S7_object"), which = TRUE)
if (class[[1]]) {
"R6"
} else if (class[[2]]) {
"S7"
} else if (isS4(x)) {
"S4"
} else {
"S3"
}
}((chr: CHR<> | 'chr & (CHR | v('I1085))<~@"[", ...>, sep: (vec1 | null)?, final: any?) -> CHR<> | (CHR | v('I1085))<~@"[", ...> & 'chr)<>| parameter | change | call | returned |
|---|---|---|---|
| chr | kind:null | oxford_comma(NULL, -2.5, as.name("x")) | null |
| chr | kind:sym | oxford_comma(as.name("x"), as.raw(c(255)), NULL) | sym |
| chr | wrap | oxford_comma(list(c("", "NA"))) | { (CHR & ~vec1)<> with { } }<> with { } |
| call | verdict | error |
|---|---|---|
| oxford_comma(c("x y", "NA"), as.raw(c(255)), NULL) | error_type | base::paste: invalid 'collapse' argument |
| oxford_comma(c("x y", ""), as.raw(c(0))) | error_type | base::paste: invalid 'collapse' argument |
| oxford_comma(c("x y", ""), 1000000L, "final" = quote(f(x))) | error_type | base::paste: invalid 'collapse' argument |
| oxford_comma(c(NA_character_, "é"), "sep" = complex(real = 1, imaginary = -2), "final" = as.name("x")) | error_type | base::paste: invalid 'collapse' argument |
| oxford_comma("chr" = c("", "x y"), "final" = local({ p <- unserialize(serialize(new("externalptr"), NULL)); attributes(p) <- NULL; p })) | error_type | base::paste0: cannot coerce type 'externalptr' to vector of type 'character' |
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)
}
}Failure("Unsupported argument after an ellipsis.")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)
}
if (inherits(arg, "AsIs")) {
format_arg <- identity
} else {
format_arg <- cli$format_arg
}
message <- sprintf(
"%s must be %s, not %s.",
format_arg(arg),
what,
obj_type_friendly(x, value = show_value)
)
abort(message, ..., call = call, arg = arg)
}.Call — a name the prelude does not declarename: .Call
.standalone_types_check_dot_call <- .CallFailure("Unsupported argument after an ellipsis.")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
)
}is_string — a name the prelude does not declarename: is_string
.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
}Failure("Unsupported argument after an ellipsis.")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
)
}Failure("Unsupported argument after an ellipsis.")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 <- 0IS_NUMBER_false <- 1IS_NUMBER_oob <- 2Failure("Unsupported argument after an ellipsis.").stop_not_number <- function(x,
...,
exit_code,
allow_decimal,
min,
max,
allow_na,
allow_null,
arg,
call) {
if (allow_decimal) {
what <- "a number"
} else {
what <- "a whole number"
}
if (exit_code == IS_NUMBER_oob) {
min <- min %||% -Inf
max <- max %||% Inf
if (min > -Inf && max < Inf) {
what <- sprintf("%s between %s and %s", what, min, max)
} else if (x < min) {
what <- sprintf("%s larger than or equal to %s", what, min)
} else if (x > max) {
what <- sprintf("%s smaller than or equal to %s", what, max)
} else {
abort("Unexpected state in OOB check", .internal = TRUE)
}
}
stop_input_type(
x,
what,
...,
allow_na = allow_na,
allow_null = allow_null,
arg = arg,
call = call
)
}Failure("Unsupported argument after an ellipsis.")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
)
}Failure("Unsupported argument after an ellipsis.")check_number_whole <- function(x,
...,
min = NULL,
max = NULL,
allow_infinite = FALSE,
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,
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
)
}Failure("Unsupported argument after an ellipsis.")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_na = FALSE,
allow_null = allow_null,
arg = arg,
call = call
)
}Failure("Unsupported argument after an ellipsis.")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_na = FALSE,
allow_null = allow_null,
arg = arg,
call = call
)
}Failure("Unsupported argument after an ellipsis.")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_na = FALSE,
allow_null = allow_null,
arg = arg,
call = call
)
}Failure("Unsupported argument after an ellipsis.")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_na = FALSE,
allow_null = allow_null,
arg = arg,
call = call
)
}Failure("Unsupported argument after an ellipsis.")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_na = FALSE,
allow_null = allow_null,
arg = arg,
call = call
)
}Failure("Unsupported argument after an ellipsis.")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_na = FALSE,
allow_null = allow_null,
arg = arg,
call = call
)
}Failure("Unsupported argument after an ellipsis.")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_na = FALSE,
allow_null = allow_null,
arg = arg,
call = call
)
}Failure("Unsupported argument after an ellipsis.")check_character <- function(x,
...,
allow_na = TRUE,
allow_null = FALSE,
arg = caller_arg(x),
call = caller_env()) {
if (!missing(x)) {
if (is_character(x)) {
if (!allow_na && any(is.na(x))) {
abort(
sprintf("`%s` can't contain NA values.", arg),
arg = arg,
call = call
)
}
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
)
}Failure("Unsupported argument after an ellipsis.")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_na = FALSE,
allow_null = allow_null,
arg = arg,
call = call
)
}Failure("Unsupported argument after an ellipsis.")check_data_frame <- function(x,
...,
allow_null = FALSE,
arg = caller_arg(x),
call = caller_env()) {
if (!missing(x)) {
if (is.data.frame(x)) {
return(invisible(NULL))
}
if (allow_null && is_null(x)) {
return(invisible(NULL))
}
}
stop_input_type(
x,
"a data frame",
...,
allow_null = allow_null,
arg = arg,
call = call
)
}vec_size — a name the prelude does not declarename: vec_size
df_append <- function(x, y, after = NULL, remove = FALSE) {
size <- vec_size(x)
row_names <- .row_names_info(x, type = 0L)
x <- tidyr_new_list(x)
y <- tidyr_new_list(y)
x_names <- names(x)
y_names <- names(y)
n <- length(x)
if (is.null(after)) {
after <- n
} else if (is.character(after)) {
after <- match(after, x_names)
}
# r-lib/rlang#1702
check_number_whole(after, min = 0, max = as.numeric(n), .internal = TRUE)
if (remove) {
lhs <- seq2(1L, after - 1L)
} else {
lhs <- seq2(1L, after)
}
rhs <- seq2(after + 1L, n)
# Prefer `y` if names are duplicated
lhs <- setdiff(x_names[lhs], y_names)
rhs <- setdiff(x_names[rhs], y_names)
out <- vec_c(x[lhs], y, x[rhs])
out <- new_data_frame(out, n = size, row.names = row_names)
out
}vec_ptype — a name the prelude does not declarename: vec_ptype
col_chop <- function(x, indices) {
ptype <- vec_ptype(x)
out <- vec_chop(x, indices)
out <- new_list_of(out, ptype)
out
}current_env — a name the prelude does not declarename: current_env
chop <- function(data, cols, ..., error_call = current_env()) {
check_dots_empty0(...)
check_data_frame(data, call = error_call)
check_required(cols, call = error_call)
cols <- tidyselect::eval_select(
expr = enquo(cols),
data = data,
allow_rename = FALSE,
error_call = error_call
)
cols <- tidyr_new_list(data[cols])
keys <- data[setdiff(names(data), names(cols))]
info <- vec_group_loc(keys)
keys <- info$key
indices <- info$loc
size <- vec_size(keys)
cols <- map(cols, col_chop, indices = indices)
cols <- new_data_frame(cols, n = size)
out <- vec_cbind(keys, cols, .error_call = error_call)
reconstruct_tibble(data, out)
}((x: 'x, sizes: 'sizes, x_nulls: any, keep_empty: tt) -> { x: 'x, sizes: 'sizes }<>)<>| parameter | change | call | returned |
|---|---|---|---|
| x | drop | unchop_finalize(complex(0), new.env(), "keep_empty" = TRUE) | { x: (CLX & ~vec1)<> with { }, sizes: env<> with { } }<> with { names: (CHR & ~vec1)<> with { } } |
unchop_finalize <- function(x, sizes, x_nulls, keep_empty) {
if (keep_empty) {
return(list(x = x, sizes = sizes))
}
# If !keep_empty, `NULL` elements were temporarily given size 1L and
# converted to a size 1 missing equivalent for recycling. However, if the
# entire row was made up of `NULL`s, then we need to adjust the size back to
# 0L and convert back to `NULL`s since that row should be dropped.
null_row <- reduce(x_nulls, `&`)
if (any(null_row)) {
sizes[null_row] <- 0L
x <- vec_assign(x, null_row, vec_init(x, n = 1L))
}
list(x = x, sizes = sizes)
}((x: { }<@"[", @"[[", `I178>, y: { }<~@"[", ...>, error_call: any) -> { }<@"[", @"[[", `I178>)<>| parameter | change | call | returned |
|---|---|---|---|
| error_call | drop | unchop_sizes2("x" = list(), "y" = list()) | { }<> with { } |
| error_call | drop | unchop_sizes2(list(), "y" = list()) | { }<> with { } |
| x | kind:dbl | unchop_sizes2("x" = 1.5, "y" = list(), "error_call" = list(NA_integer_)) | (^DBL1 \ (..))<> with { } |
| x | kind:lang | unchop_sizes2(quote(f(x)), list(), "error_call" = list()) | lang<> with { } |
| y | drop | unchop_sizes2(list(), quote(f(x))) | { }<> with { } |
| y | kind:chr | unchop_sizes2(list(), "fuzz", "error_call" = as.raw(c(255))) | { }<> with { } |
unchop_sizes2 <- function(x, y, error_call) {
# Standard tidyverse recycling rules, just vectorized.
# Recycle `x` values with `y`
x_one <- x == 1L
if (any(x_one)) {
x[x_one] <- y[x_one]
}
# Recycle `y` values with `x`.
# Only necessary to be able to check for incompatibilities.
y_one <- y == 1L
if (any(y_one)) {
y[y_one] <- x[y_one]
}
# Check for incompatibilities
incompatible <- x != y
if (any(incompatible)) {
row <- which(incompatible)[[1]]
x <- x[[row]]
y <- y[[row]]
cli::cli_abort(
"In row {row}, can't recycle input of size {x} to size {y}.",
call = error_call
)
}
x
}caller_env — a name the prelude does not declarename: caller_env
df_unchop <- function(
x,
...,
ptype = NULL,
keep_empty = FALSE,
error_call = caller_env()
) {
check_dots_empty()
ptype <- check_list_of_ptypes(ptype, names = names(x), call = error_call)
size <- vec_size(x)
# Avoid any data frame subclass method dispatch
x <- new_data_frame(x, n = size)
width <- length(x)
x_names <- names(x)
seq_len_width <- seq_len(width)
seq_len_size <- seq_len(size)
if (width == 0L) {
# Algorithm requires >=1 columns
out <- list(loc = seq_len_size, val = x)
out <- new_data_frame(out, n = size)
return(out)
}
x_ptypes <- map2(x, x_names, function(col, name) {
ptype[[name]] %||% list_of_ptype(col)
})
x_is_list <- map_lgl(x, vec_is_list)
x_sizes <- vector("list", length = width)
x_nulls <- vector("list", length = width)
for (i in seq_len_width) {
col <- x[[i]]
col_name <- x_names[[i]]
col_ptype <- x_ptypes[[i]]
col_is_list <- x_is_list[[i]]
if (!col_is_list) {
# Optimize rare non list-cols
x_sizes[[i]] <- vec_rep(1L, size)
x_nulls[[i]] <- vec_rep(FALSE, size)
next
}
col <- tidyr_new_list(col)
col_sizes <- list_sizes(col)
col_nulls <- vec_detect_missing(col)
# Always replace `NULL` elements with size 1 missing equivalent for recycling.
# These will be reset to `NULL` in `unchop_finalize()` if the
# entire row was missing and `keep_empty = FALSE`.
info <- list_replace_null(col, col_sizes, ptype = col_ptype)
col <- info$x
col_sizes <- info$sizes
if (keep_empty) {
info <- list_replace_empty_typed(col, col_sizes, ptype = col_ptype)
col <- info$x
col_sizes <- info$sizes
}
x[[i]] <- col
x_sizes[[i]] <- col_sizes
x_nulls[[i]] <- col_nulls
}
sizes <- reduce(x_sizes, unchop_sizes2, error_call = error_call)
info <- unchop_finalize(x, sizes, x_nulls, keep_empty)
x <- info$x
sizes <- info$sizes
out_loc <- vec_rep_each(seq_len_size, sizes)
out_size <- sum(sizes)
out_cols <- vector("list", length = width)
for (i in seq_len_width) {
col <- x[[i]]
col_name <- x_names[[i]]
col_ptype <- x_ptypes[[i]]
col_is_list <- x_is_list[[i]]
col_sizes <- x_sizes[[i]]
if (!col_is_list) {
# Optimize rare non list-cols
if (!is_null(col_ptype)) {
col <- vec_cast(
x = col,
to = col_ptype,
x_arg = col_name,
call = error_call
)
}
out_cols[[i]] <- vec_slice(col, out_loc)
next
}
# Drop outer names because inner elements have varying size
col <- unname(col)
row_recycle <- col_sizes != sizes
col[row_recycle] <- map2(
col[row_recycle],
sizes[row_recycle],
vec_recycle,
call = error_call
)
col <- list_unchop(
x = col,
ptype = col_ptype,
error_arg = col_name,
error_call = error_call
)
if (is_null(col)) {
# This can happen when both of these are true:
# - `col` was an empty list(), or a list of all `NULL`s.
# - No ptype was specified for `col`, either by the user or by a list-of.
if (out_size != 0L) {
cli::cli_abort(
"`NULL` column generated, but output size is not `0`.",
.internal = TRUE
)
}
col <- unspecified(0L)
}
out_cols[[i]] <- col
}
names(out_cols) <- x_names
out_val <- new_data_frame(out_cols, n = out_size)
out <- list(loc = out_loc, val = out_val)
out <- new_data_frame(out, n = out_size)
out
}current_env — a name the prelude does not declarename: current_env
unchop <- function(
data,
cols,
...,
keep_empty = FALSE,
ptype = NULL,
error_call = current_env()
) {
check_dots_empty0(...)
check_data_frame(data, call = error_call)
check_required(cols, call = error_call)
check_bool(keep_empty, call = error_call)
sel <- tidyselect::eval_select(
expr = enquo(cols),
data = data,
allow_rename = FALSE,
error_call = error_call
)
size <- vec_size(data)
names <- names(data)
# Start from first principles to avoid issues in any subclass methods
out <- new_data_frame(data, n = size)
cols <- out[sel]
# Remove unchopped columns to avoid slicing them needlessly later
out[sel] <- NULL
result <- df_unchop(
x = cols,
ptype = ptype,
keep_empty = keep_empty,
error_call = error_call
)
cols <- result$val
loc <- result$loc
out <- vec_slice(out, loc)
# Add unchopped columns back on then preserve original ordering
out <- tidyr_col_modify(out, cols)
out <- out[names]
reconstruct_tibble(data, out)
}check_dots_unnamed — a name the prelude does not declarename: check_dots_unnamed
fill <- function(
data,
...,
.by = NULL,
.direction = c("down", "up", "downup", "updown")
) {
check_dots_unnamed()
UseMethod("fill")
}Failure("Unsupported positional argument after a named one.")fill.data.frame <- function(
data,
...,
.by = NULL,
.direction = c("down", "up", "downup", "updown")
) {
vars <- names(tidyselect::eval_select(
expr = expr(c(...)),
data = data,
allow_rename = FALSE
))
.direction <- arg_match0(
arg = .direction,
values = c("down", "up", "downup", "updown"),
)
fn <- function(col) {
vec_fill_missing(col, direction = .direction)
}
dplyr::mutate(
data,
dplyr::across(any_of(vars), .fns = fn),
.by = {{ .by }}
)
}is_null — a name the prelude does not declarename: is_null
id_var <- function(x, drop = FALSE) {
if (!is_null(attr(x, "n", exact = TRUE)) && !drop) {
return(x)
}
if (is.factor(x) && !drop) {
x_na <- addNA(x, ifany = TRUE)
id <- as.integer(x_na)
n <- length(levels(x_na))
} else if (length(x) == 0) {
id <- integer()
n <- 0L
} else if (is_list(x)) {
# Sorting lists isn't supported
levels <- unique(x)
id <- match(x, levels)
n <- max(id)
} else {
levels <- sort(unique(x), na.last = TRUE)
id <- match(x, levels)
n <- max(id)
}
structure(id, n = n)
}id_var — one of the package’s own names, itself untypedname: id_var
id <- function(.variables, drop = FALSE) {
if (length(.variables) == 0) {
n <- nrow(.variables) %||% 0L
return(structure(seq_len(n), n = n))
}
# Special case for single variable
if (length(.variables) == 1) {
return(id_var(.variables[[1]], drop = drop))
}
# Calculate individual ids
ids <- rev(map(.variables, id_var, drop = drop))
p <- length(ids)
# Calculate dimensions
ndistinct <- map_dbl(ids, attr, "n")
n <- prod(ndistinct)
if (n > 2^31) {
# Too big for integers, have to use strings, which will be much slower :(
char_id <- do.call("paste", c(ids, sep = "\r"))
res <- match(char_id, unique(char_id))
} else {
combs <- c(1, cumprod(ndistinct[-p]))
mat <- do.call("cbind", ids)
res <- c((mat - 1L) %*% combs + 1L)
}
attr(res, "n") <- n
if (drop) {
id_var(res, drop = TRUE)
} else {
structure(as.integer(res), n = attr(res, "n"))
}
}UseMethod — a name the prelude does not declarename: UseMethod
spread <- function(
data,
key,
value,
fill = NA,
convert = FALSE,
drop = TRUE,
sep = NULL
) {
UseMethod("spread")
}argument: any argument may be: new.env()
as_tibble_matrix <- function(x) {
# getS3method() only available in R >= 3.3
get("as_tibble.matrix", asNamespace("tibble"), mode = "function")(x)
}col_names <- function(x, sep = NULL) {
names <- as.character(x[[1]])
if (is_null(sep)) {
if (length(names) == 0) {
# ifelse will return logical()
character()
} else {
ifelse(are_na(names), "<NA>", names)
}
} else {
paste(names(x)[[1]], names, sep = sep)
}
}addNA — a name the prelude does not declarename: addNA
ulevels <- function(x) {
if (is.factor(x)) {
orig_levs <- levels(x)
x <- addNA(x, ifany = TRUE)
levs <- levels(x)
factor(levs, levels = orig_levs, ordered = is.ordered(x), exclude = NULL)
} else if (is.list(x)) {
unique(x)
} else {
sort(unique(x), na.last = TRUE)
}
}unique — a name the prelude does not declarename: unique
split_labels <- function(df, id, drop = TRUE) {
if (length(df) == 0) {
return(df)
}
if (drop) {
representative <- match(sort(unique(id)), id)
out <- df[representative, , drop = FALSE]
rownames(out) <- NULL
out
} else {
unique_values <- map(df, ulevels)
rev(expand.grid(rev(unique_values), stringsAsFactors = FALSE))
}
}Failure("Unsupported positional argument after a named one.")spread.data.frame <- function(
data,
key,
value,
fill = NA,
convert = FALSE,
drop = TRUE,
sep = NULL
) {
key_var <- tidyselect::vars_pull(names(data), !!enquo(key))
value_var <- tidyselect::vars_pull(names(data), !!enquo(value))
col <- data[key_var]
col_id <- id(col, drop = drop)
col_labels <- split_labels(col, col_id, drop = drop)
rows <- data[setdiff(names(data), c(key_var, value_var))]
if (ncol(rows) == 0 && nrow(rows) > 0) {
# Special case when there's only one row
row_id <- structure(1L, n = 1L)
row_labels <- as.data.frame(matrix(nrow = 1, ncol = 0))
} else {
row_id <- id(rows, drop = drop)
row_labels <- split_labels(rows, row_id, drop = drop)
rownames(row_labels) <- NULL
}
overall <- id(list(col_id, row_id), drop = FALSE)
n <- attr(overall, "n")
# Check that each output value occurs in unique location
if (anyDuplicated(overall)) {
groups <- split(seq_along(overall), overall)
groups <- groups[map_int(groups, length) > 1]
shared <- sum(map_int(groups, length))
str <- map_chr(groups, function(x) paste0(x, collapse = ", "))
cli::cli_abort(c(
"Each row of output must be identified by a unique combination of keys.",
i = "Keys are shared for {shared} rows",
set_names(str, "*")
))
}
# Add in missing values, if necessary
if (length(overall) < n) {
overall <- match(seq_len(n), overall, nomatch = NA)
} else {
overall <- order(overall)
}
value <- data[[value_var]]
ordered <- value[overall]
if (!is.na(fill)) {
ordered[is.na(ordered)] <- fill
}
if (convert && !is_character(ordered)) {
ordered <- as.character(ordered)
}
dim(ordered) <- c(attr(row_id, "n"), attr(col_id, "n"))
colnames(ordered) <- enc2utf8(col_names(col_labels, sep = sep))
ordered <- as_tibble_matrix(ordered)
if (convert) {
ordered[] <- map(ordered, type.convert, as.is = TRUE)
}
out <- df_append(row_labels, ordered)
reconstruct_tibble(data, out, c(key_var, value_var))
}UseMethod — a name the prelude does not declarename: UseMethod
expand <- function(data, ..., .name_repair = "check_unique") {
UseMethod("expand")
}caller_env — a name the prelude does not declarename: caller_env
grid_dots <- function(..., `_data` = NULL, .error_call = caller_env()) {
dots <- enquos(...)
n_dots <- length(dots)
names <- names(dots)
needs_auto_name <- names == ""
# Silently uniquely repair "auto-names" to avoid collisions
# from truncated long names. Probably not a perfect system, but solves
# most of the reported issues.
auto_names <- names(exprs_auto_name(
exprs = dots[needs_auto_name],
repair_auto = "unique",
repair_quiet = TRUE
))
names[needs_auto_name] <- auto_names
# Set up a mask for repeated `eval_tidy()` calls that support iterative
# expressions
env <- new_environment()
mask <- new_data_mask(env)
mask$.data <- as_data_pronoun(env)
if (!is.null(`_data`)) {
# Pre-load the data mask with `_data`
cols <- tidyr_new_list(`_data`)
col_names <- names(cols)
for (i in seq_along(cols)) {
col <- cols[[i]]
col_name <- col_names[[i]]
env[[col_name]] <- col
}
}
out <- vector("list", length = n_dots)
null <- vector("logical", length = n_dots)
for (i in seq_len(n_dots)) {
dot <- dots[[i]]
dot <- eval_tidy(dot, data = mask)
if (is.null(dot)) {
null[[i]] <- TRUE
next
}
arg <- paste0("..", i)
vec_assert(dot, arg = arg, call = .error_call)
out[[i]] <- dot
is_unnamed_data_frame <- is.data.frame(dot) && needs_auto_name[[i]]
if (is_unnamed_data_frame) {
# Signal that unnamed data frame should be spliced by setting its name
# to `""`. Then add its individual columns into the mask.
names[[i]] <- ""
dot_names <- names(dot)
for (i in seq_along(dot)) {
dot_col <- dot[[i]]
dot_name <- dot_names[[i]]
env[[dot_name]] <- dot_col
}
} else {
# Install `dot` in the mask for iterative evaluations
name <- names[[i]]
env[[name]] <- dot
}
}
if (any(null)) {
out <- out[!null]
names <- names[!null]
}
names(out) <- names
out
}grid_dots — one of the package’s own names, itself untypedname: grid_dots
expand_grid <- function(..., .name_repair = "check_unique", .vary = "slowest") {
out <- grid_dots(...)
names <- names2(out)
unnamed <- which(names == "")
any_unnamed <- any(unnamed)
if (any_unnamed) {
# `vec_expand_grid()` requires all inputs to be named.
# Most are auto named by `grid_dots()`, but unnamed data frames are not.
# So we temporarily name unnamed data frames that eventually get spliced.
names[unnamed] <- vec_paste0("...", unnamed)
names(out) <- names
}
out <- vec_expand_grid(
!!!out,
.vary = .vary,
.name_repair = "minimal",
.error_call = current_env()
)
if (any_unnamed) {
names[unnamed] <- ""
names(out) <- names
}
size <- vec_size(out)
# Flattens unnamed data frames after grid expansion
out <- tidyr_new_list(out)
out <- df_list(
!!!out,
.name_repair = .name_repair,
.error_call = current_env()
)
out <- tibble::new_tibble(out, nrow = size)
out
}anyNA — a name the prelude does not declarename: anyNA
fct_unique <- function(x) {
levels <- levels(x)
out <- levels
if (!anyNA(levels) && anyNA(x)) {
out <- c(out, NA_character_)
}
factor(out, levels = levels, exclude = NULL, ordered = is.ordered(x))
}fct_unique — one of the package’s own names, itself untypedname: fct_unique
sorted_unique <- function(x) {
if (is.factor(x)) {
fct_unique(x)
} else if (is_bare_list(x)) {
vec_unique(x)
} else {
vec_sort(vec_unique(x))
}
}Failure("Unsupported argument after an ellipsis.")expand.data.frame <- function(data, ..., .name_repair = "check_unique") {
out <- grid_dots(..., `_data` = data)
out <- map(out, sorted_unique)
# Flattens unnamed data frames returned from `grid_dots()`
out <- expand_grid(!!!out, .name_repair = .name_repair)
reconstruct_tibble(data, out)
}Failure("Unsupported argument after an ellipsis.")expand.grouped_df <- function(data, ..., .name_repair = "check_unique") {
out <- dplyr::reframe(
data,
expand(
data = dplyr::pick(everything()),
...,
.name_repair = .name_repair
)
)
drop <- dplyr::group_by_drop_default(data)
dplyr::group_by(
out,
!!!dplyr::groups(data),
.drop = drop
)
}grid_dots — one of the package’s own names, itself untypedname: grid_dots
crossing <- function(..., .name_repair = "check_unique") {
out <- grid_dots(...)
out <- map(out, sorted_unique)
# Flattens unnamed data frames returned from `grid_dots()`
expand_grid(!!!out, .name_repair = .name_repair)
}grid_dots — one of the package’s own names, itself untypedname: grid_dots
nesting <- function(..., .name_repair = "check_unique") {
out <- grid_dots(...)
if (length(out) == 0L) {
# This matches `crossing()`, `expand_grid()`, and `expand()`, which return
# a 1 row / 0 col tibble. Computations involving the number of combinations
# of an empty set should return 1.
size <- 1L
} else {
size <- NULL
}
# Flattens unnamed data frames
out <- data_frame(!!!out, .size = size, .name_repair = .name_repair)
out <- tibble::new_tibble(out, nrow = vec_size(out))
out <- sorted_unique(out)
out
}check_dots_used — a name the prelude does not declarename: check_dots_used
replace_na <- function(data, replace, ...) {
check_dots_used()
UseMethod("replace_na")
}caller_env — a name the prelude does not declarename: caller_env
check_replacement <- function(x, var, call = caller_env()) {
n <- vec_size(x)
if (n != 1) {
cli::cli_abort(
"Replacement for `{var}` must be length 1, not length {n}.",
call = call
)
}
}check_replacement — one of the package’s own names, itself untypedname: check_replacement
replace_na.default <- function(data, replace = NA, ...) {
check_replacement(replace, "data")
if (vec_any_missing(data)) {
missing <- vec_detect_missing(data)
data <- vec_assign(
data,
missing,
replace,
x_arg = "data",
value_arg = "replace"
)
}
data
}vec_is_list — a name the prelude does not declarename: vec_is_list
replace_na.data.frame <- function(data, replace = list(), ...) {
if (!vec_is_list(replace)) {
cli::cli_abort(
"{.arg replace} must be a list, not {.obj_type_friendly {replace}}."
)
}
names <- intersect(names(replace), names(data))
col_args <- as.character(glue("data${names}"))
value_args <- as.character(glue("replace${names}"))
for (i in seq_along(names)) {
name <- names[[i]]
col <- data[[name]]
value <- replace[[name]]
col_arg <- col_args[[i]]
value_arg <- value_args[[i]]
check_replacement(value, col_arg)
if (vec_any_missing(col)) {
missing <- vec_detect_missing(col)
data[[name]] <- vec_assign(
x = col,
i = missing,
value = value,
x_arg = col_arg,
value_arg = value_arg
)
}
}
data
}UseMethod — a name the prelude does not declarename: UseMethod
complete <- function(data, ..., fill = list(), explicit = TRUE) {
UseMethod("complete")
}check_bool — one of the package’s own names, itself untypedname: check_bool
complete.data.frame <- function(data, ..., fill = list(), explicit = TRUE) {
check_bool(explicit)
out <- expand(data, ...)
names <- names(out)
if (length(names) > 0L) {
out <- dplyr::full_join(out, data, by = names, multiple = "all")
} else {
# Avoid joining the 1x0 result from `expand()` with `data`.
# That causes issues when `data` has zero rows.
out <- data
}
if (explicit) {
out <- replace_na(out, replace = fill)
} else {
new <- !vec_in(out[names], data[names])
slice <- vec_slice(out, new)
slice <- replace_na(slice, replace = fill)
out <- vec_assign(out, new, slice)
}
reconstruct_tibble(data, out)
}Failure("Unsupported argument after an ellipsis.")complete.grouped_df <- function(data, ..., fill = list(), explicit = TRUE) {
out <- dplyr::reframe(
data,
complete(
data = dplyr::pick(everything()),
...,
fill = fill,
explicit = explicit
)
)
drop <- dplyr::group_by_drop_default(data)
dplyr::group_by(
out,
!!!dplyr::groups(data),
.drop = drop
)
}_tidyr_melt_dataframe — a native symbol tyr could not bindname: _tidyr_melt_dataframe
melt_dataframe <- function(data, id_ind, measure_ind, variable_name, value_name, attrTemplate, factorsAsStrings, valueAsFactor, variableAsFactor) {
.Call(`_tidyr_melt_dataframe`, data, id_ind, measure_ind, variable_name, value_name, attrTemplate, factorsAsStrings, valueAsFactor, variableAsFactor)
}_tidyr_simplifyPieces — a native symbol tyr could not bindname: _tidyr_simplifyPieces
simplifyPieces <- function(pieces, p, fillLeft) {
.Call(`_tidyr_simplifyPieces`, pieces, p, fillLeft)
}"who""who2""population""table1""table2""table3""table4a""table4b""table5""smiths""us_rent_income""fish_encounters""world_bank_pop""relig_income""construction""billboard""household""cms_patient_experience""cms_patient_care"message — a name the prelude does not declarename: message
extract_numeric <- function(x) {
message(
"extract_numeric() is deprecated: please use readr::parse_number() instead"
)
as.numeric(gsub("[^0-9.-]+", "", as.character(x)))
}check_dots_unnamed — a name the prelude does not declarename: check_dots_unnamed
drop_na <- function(data, ...) {
check_dots_unnamed()
UseMethod("drop_na")
}enquos — a name the prelude does not declarename: enquos
drop_na.data.frame <- function(data, ...) {
dots <- enquos(...)
if (is_empty(dots)) {
# Use all columns if no `...` are supplied
cols <- data
} else {
vars <- tidyselect::eval_select(
expr(c(!!!dots)),
data,
allow_rename = FALSE
)
cols <- data[vars]
}
loc <- vec_detect_complete(cols)
out <- vec_slice(data, loc)
reconstruct_tibble(data, out)
}check_dots_used — a name the prelude does not declarename: check_dots_used
separate <- function(
data,
col,
into,
sep = "[^[:alnum:]]+",
remove = TRUE,
convert = FALSE,
extra = "warn",
fill = "warn",
...
) {
check_dots_used()
UseMethod("separate")
}caller_arg — a name the prelude does not declarename: caller_arg
check_not_stringr_pattern <- function(
x,
arg = caller_arg(x),
call = caller_env()
) {
if (inherits_any(x, c("pattern", "stringr_pattern"))) {
cli::cli_abort(
"{.arg {arg}} can't use modifiers from stringr.",
call = call
)
}
}| parameter | change | call | returned |
|---|---|---|---|
| x | wrap | list_indices(list(c(42L, -2147483647L, 2L, NA_integer_, NA_integer_))) | "c(42, -2147483647, 2, NA, NA)"<> with { } |
| x | wrap | list_indices("x" = list(as.raw(c(0, 0)))) | "as.raw(c(0x00, 0x00))"<> with { } |
| x | wrap | list_indices("x" = list(2)) | "2"<> with { } |
| x | wrap | list_indices(list(c(0.5, Inf, 42, NA_real_, 0)), 42L) | "c(0.5, Inf, 42, NA, 0)"<> with { } |
list_indices <- function(x, max = 20) {
if (length(x) > max) {
x <- c(x[seq_len(max)], "...")
}
paste(x, collapse = ", ")
}slice_match <- function(x, i) {
structure(
x[i],
match.length = attr(x, "match.length")[i],
index.type = attr(x, "index.type"),
useBytes = attr(x, "useBytes")
)
}gregexpr — a name the prelude does not declarename: gregexpr
str_split_n <- function(x, pattern, n_max = -1) {
if (is.factor(x)) {
x <- as.character(x)
}
m <- gregexpr(pattern, x, perl = TRUE)
if (n_max > 0) {
m <- map(m, function(x) slice_match(x, seq_along(x) < n_max))
}
regmatches(x, m, invert = TRUE)
}arg_match — a name the prelude does not declarename: arg_match
str_split_fixed <- function(value, sep, n, extra = "warn", fill = "warn") {
if (extra == "error") {
warn(glue(
"`extra = \"error\"` is deprecated. \\
Please use `extra = \"warn\"` instead"
))
extra <- "warn"
}
extra <- arg_match(extra, c("warn", "merge", "drop"))
fill <- arg_match(fill, c("warn", "left", "right"))
n_max <- if (extra == "merge") n else -1L
pieces <- str_split_n(value, sep, n_max = n_max)
simp <- simplifyPieces(pieces, n, fill == "left")
n_big <- length(simp$too_big)
if (extra == "warn" && n_big > 0) {
idx <- list_indices(simp$too_big)
warn(glue(
"Expected {n} pieces. Additional pieces discarded in {n_big} rows [{idx}]."
))
}
n_sml <- length(simp$too_sml)
if (fill == "warn" && n_sml > 0) {
idx <- list_indices(simp$too_sml)
warn(glue(
"Expected {n} pieces. Missing pieces filled with `NA` in {n_sml} rows [{idx}]."
))
}
simp$strings
}pmax — a name the prelude does not declarename: pmax
strsep <- function(x, sep) {
nchar <- nchar(x)
pos <- map(sep, function(i) {
if (i >= 0) {
i
} else {
pmax(0, nchar + i)
}
})
pos <- c(list(0), pos, list(nchar))
map(1:(length(pos) - 1), function(i) {
substr(x, pos[[i]] + 1, pos[[i + 1]])
})
}caller_env — a name the prelude does not declarename: caller_env
str_separate <- function(
x,
into,
sep,
convert = FALSE,
extra = "warn",
fill = "warn",
error_call = caller_env()
) {
check_character(into, call = error_call)
check_bool(convert, call = error_call)
if (is.numeric(sep)) {
out <- strsep(x, sep)
} else if (is_string(sep)) {
check_not_stringr_pattern(sep, call = error_call)
out <- str_split_fixed(x, sep, length(into), extra = extra, fill = fill)
} else {
cli::cli_abort(
"{.arg sep} must be a string or numeric vector, not {.obj_type_friendly {sep}}",
call = error_call
)
}
names(out) <- as_utf8_character(into)
out <- out[!is.na(names(out))]
if (convert) {
out[] <- map(out, type.convert, as.is = TRUE)
}
as_tibble(out)
}check_required — a name the prelude does not declarename: check_required
separate.data.frame <- function(
data,
col,
into,
sep = "[^[:alnum:]]+",
remove = TRUE,
convert = FALSE,
extra = "warn",
fill = "warn",
...
) {
check_required(col)
check_bool(remove)
var <- tidyselect::vars_pull(names(data), !!enquo(col))
value <- as.character(data[[var]])
new_cols <- str_separate(
value,
into = into,
sep = sep,
convert = convert,
extra = extra,
fill = fill
)
out <- df_append(data, new_cols, var, remove = remove)
reconstruct_tibble(data, out, if (remove) var else NULL)
}check_dots_used — a name the prelude does not declarename: check_dots_used
extract <- function(
data,
col,
into,
regex = "([[:alnum:]]+)",
remove = TRUE,
convert = FALSE,
...
) {
check_dots_used()
UseMethod("extract")
}as.vector — a name the prelude does not declarename: as.vector
group_loc <- function(x) {
start <- cbind(as.vector(x), attr(x, "capture.start"))
end <- start + cbind(attr(x, "match.length"), attr(x, "capture.length")) - 1L
no_match <- start == -1L
start[no_match] <- NA
end[no_match] <- NA
list(matches = ncol(start), start = start, end = end)
}group_loc — one of the package’s own names, itself untypedname: group_loc
str_match_first <- function(string, regex) {
loc <- regexpr(regex, string, perl = TRUE)
loc <- group_loc(loc)
out <- map(
seq_len(loc$matches),
function(i) substr(string, loc$start[, i], loc$end[, i])
)
out[-1]
}caller_env — a name the prelude does not declarename: caller_env
str_extract <- function(
x,
into,
regex,
convert = FALSE,
error_call = caller_env()
) {
check_string(regex, call = error_call)
check_not_stringr_pattern(regex, call = error_call)
check_character(into, call = error_call)
check_bool(convert, call = error_call)
out <- str_match_first(x, regex)
if (length(out) != length(into)) {
cli::cli_abort(
"{.arg regex} should define {length(into)} groups; {length(out)} found.",
call = error_call
)
}
# Handle duplicated names
if (anyDuplicated(into)) {
pieces <- split(out, into)
into <- names(pieces)
out <- map(pieces, pmap_chr, vec_paste0)
}
into <- as_utf8_character(into)
non_na_into <- !is.na(into)
out <- out[non_na_into]
names(out) <- into[non_na_into]
out <- as_tibble(out)
if (convert) {
out[] <- map(out, type.convert, as.is = TRUE)
}
out
}check_required — a name the prelude does not declarename: check_required
extract.data.frame <- function(
data,
col,
into,
regex = "([[:alnum:]]+)",
remove = TRUE,
convert = FALSE,
...
) {
check_required(col)
var <- tidyselect::vars_pull(names(data), !!enquo(col))
value <- as.character(data[[var]])
new_cols <- str_extract(value, into = into, regex = regex, convert = convert)
out <- df_append(data, new_cols, var, remove = remove)
reconstruct_tibble(data, out, if (remove) var else chr())
}check_dots_unnamed — a name the prelude does not declarename: check_dots_unnamed
gather <- function(
data,
key = "key",
value = "value",
...,
na.rm = FALSE,
convert = FALSE,
factor_key = FALSE
) {
check_dots_unnamed()
UseMethod("gather")
}| parameter | change | call | returned |
|---|---|---|---|
| xs | kind:env | all_identical(new.env()) | tt<> with { } |
| xs | kind:fun | all_identical(function(...) NULL) | tt<> with { } |
| xs | kind:lang | all_identical(quote(f(x))) | ff<> with { } |
| xs | kind:null | all_identical("xs" = NULL) | tt<> with { } |
all_identical <- function(xs) {
if (length(xs) <= 1) {
return(TRUE)
}
for (i in seq(2, length(xs))) {
if (!identical(xs[[1]], xs[[i]])) {
return(FALSE)
}
}
TRUE
}map — a name the prelude does not declarename: map
normalize_melt_arguments <- function(data, measure.ind) {
measure.attributes <- map(measure.ind, function(i) {
attributes(data[[i]])
})
## Determine if all measure.attributes are equal
measure.attrs.equal <- all_identical(measure.attributes)
if (measure.attrs.equal) {
attr_template <- data[[measure.ind[1]]]
} else {
warn(glue(
"attributes are not identical across measure variables;
they will be dropped"
))
attr_template <- NULL
}
## If we are going to be coercing any factors to strings, we don't want to
## copy the attributes
any.factors <- any(map_lgl(measure.ind, function(i) is.factor(data[[i]])))
if (any.factors) {
attr_template <- NULL
}
list(
attr_template = attr_template,
factorsAsStrings = TRUE
)
}ensym — a name the prelude does not declarename: ensym
gather.data.frame <- function(
data,
key = "key",
value = "value",
...,
na.rm = FALSE,
convert = FALSE,
factor_key = FALSE
) {
key_var <- as_string(ensym(key))
value_var <- as_string(ensym(value))
quos <- quos(...)
if (is_empty(quos)) {
gather_vars <- setdiff(names(data), c(key_var, value_var))
} else {
gather_vars <- unname(tidyselect::vars_select(tbl_vars(data), !!!quos))
}
if (is_empty(gather_vars)) {
return(data)
}
gather_idx <- match(gather_vars, names(data))
id_idx <- setdiff(seq_along(data), gather_idx)
dup_indx <- match(c(key_var, value_var), names(data))
id_idx <- setdiff(id_idx, dup_indx)
## Get the attributes if common, NULL if not.
args <- normalize_melt_arguments(data, gather_idx)
valueAsFactor <- "factor" %in% class(args$attr_template)
out <- melt_dataframe(
data,
id_idx - 1L,
gather_idx - 1L,
as.character(key_var),
as.character(value_var),
args$attr_template,
args$factorsAsStrings,
as.logical(valueAsFactor),
as.logical(factor_key)
)
if (na.rm && anyNA(out)) {
missing <- is.na(out[[value_var]])
out <- out[!missing, ]
}
if (convert) {
out[[key_var]] <- type.convert(as.character(out[[key_var]]), as.is = TRUE)
}
reconstruct_tibble(data, out, gather_vars)
}warn_underscored <- function() {
return(NULL)
warn(paste(
"The underscored versions are deprecated in favour of",
"tidy evaluation idioms. Please see the documentation",
"for `quo()` in rlang"
))
}warn_text_se <- function() {
return(NULL)
warn("Text parsing is deprecated, please supply an expression or formula")
}caller_env — a name the prelude does not declarename: caller_env
compat_lazy <- function(lazy, env = caller_env(), warn = TRUE) {
if (warn) warn_underscored()
if (missing(lazy)) {
return(quo())
}
if (is_quosure(lazy)) {
return(lazy)
}
if (is_formula(lazy)) {
return(as_quosure(lazy, env))
}
out <- switch(typeof(lazy),
symbol = ,
language = new_quosure(lazy, env),
character = {
if (warn) warn_text_se()
parse_quo(lazy[[1]], env)
},
logical = ,
integer = ,
double = {
if (length(lazy) > 1) {
warn("Truncating vector to length 1")
lazy <- lazy[[1]]
}
new_quosure(lazy, env)
},
list =
if (inherits(lazy, "lazy")) {
lazy = new_quosure(lazy$expr, lazy$env)
}
)
if (is_null(out)) {
abort(sprintf("Can't convert a %s to a quosure", typeof(lazy)))
} else {
out
}
}compat_lazy — one of the package’s own names, itself untypedname: compat_lazy
compat_lazy_dots <- function(dots, env, ..., .named = FALSE) {
if (missing(dots)) {
dots <- list()
}
if (inherits(dots, c("lazy", "formula"))) {
dots <- list(dots)
} else {
dots <- unclass(dots)
}
dots <- c(dots, list(...))
warn <- TRUE
for (i in seq_along(dots)) {
dots[[i]] <- compat_lazy(dots[[i]], env, warn)
warn <- FALSE
}
named <- have_name(dots)
if (.named && any(!named)) {
nms <- vapply(dots[!named], function(x) expr_text(get_expr(x)), character(1))
names(dots)[!named] <- nms
}
names(dots) <- names2(dots)
dots
}Failure("Unsupported positional argument after a named one.")compat_as_lazy <- function(quo) {
structure(class = "lazy", list(
expr = get_expr(quo),
env = get_env(quo)
))
}Failure("Unsupported positional argument after a named one.")compat_as_lazy_dots <- function(...) {
structure(class = "lazy_dots", lapply(quos(...), compat_as_lazy))
}check_dots_unnamed — a name the prelude does not declarename: check_dots_unnamed
separate_rows <- function(data, ..., sep = "[^[:alnum:].]+", convert = FALSE) {
check_dots_unnamed()
UseMethod("separate_rows")
}check_string — one of the package’s own names, itself untypedname: check_string
separate_rows.data.frame <- function(
data,
...,
sep = "[^[:alnum:].]+",
convert = FALSE
) {
check_string(sep)
check_bool(convert)
vars <- tidyselect::eval_select(expr(c(...)), data, allow_rename = FALSE)
vars <- names(vars)
out <- purrr::modify_at(data, vars, str_split_n, pattern = sep)
out <- unchop(as_tibble(out), any_of(vars), error_call = current_env())
if (convert) {
out[vars] <- map(out[vars], type.convert, as.is = TRUE)
}
reconstruct_tibble(data, out, vars)
}check_dots_unnamed — a name the prelude does not declarename: check_dots_unnamed
unite <- function(data, col, ..., sep = "_", remove = TRUE, na.rm = FALSE) {
check_dots_unnamed()
UseMethod("unite")
}check_required — a name the prelude does not declarename: check_required
unite.data.frame <- function(
data,
col,
...,
sep = "_",
remove = TRUE,
na.rm = FALSE
) {
check_required(col)
check_string(sep)
check_bool(remove)
check_bool(na.rm)
col <- as_string(ensym(col))
col <- enc2utf8(col)
if (dots_n(...) == 0) {
selection <- set_names(seq_along(data), names(data))
} else {
selection <- tidyselect::eval_select(
expr(c(...)),
data,
allow_rename = FALSE
)
}
empty_selection <- length(selection) == 0L
out <- data
if (remove) {
out <- out[setdiff(names(out), names(selection))]
}
if (empty_selection) {
# Use initial value implied by the reduction algorithm (#1570)
united <- vec_rep("", times = vec_size(data))
} else if (identical(na.rm, TRUE)) {
cols <- unname(map(data[selection], as.character))
rows <- transpose(cols)
united <- map_chr(rows, function(x) paste0(x[!is.na(x)], collapse = sep))
} else {
cols <- unname(as.list(data[selection]))
united <- exec(paste, !!!cols, sep = sep)
}
united <- list(united)
names(united) <- col
if (empty_selection) {
after <- length(data)
} else {
loc_first_selection <- which(names(data) %in% names(selection))[[1L]]
after <- loc_first_selection - 1L
}
out <- df_append(out, united, after = after)
reconstruct_tibble(
input = data,
output = out,
ungrouped_vars = if (remove) names(selection)
)
}NULLlifecycle::deprecate_warn — a name the prelude does not declarename: lifecycle::deprecate_warn
complete_ <- function(data, cols, fill = list(), ...) {
lifecycle::deprecate_warn("1.0.0", "complete_()", "complete()", always = TRUE)
UseMethod("complete_")
}caller_env — a name the prelude does not declarename: caller_env
complete_.data.frame <- function(data, cols, fill = list(), ...) {
cols <- compat_lazy_dots(cols, caller_env())
complete(data, !!!cols, fill = fill)
}lifecycle::deprecate_warn — a name the prelude does not declarename: lifecycle::deprecate_warn
drop_na_ <- function(data, vars) {
lifecycle::deprecate_warn("1.0.0", "drop_na_()", "drop_na()", always = TRUE)
UseMethod("drop_na_")
}drop_na — one of the package’s own names, itself untypedname: drop_na
drop_na_.data.frame <- function(data, vars) {
drop_na(data, !!!vars)
}lifecycle::deprecate_warn — a name the prelude does not declarename: lifecycle::deprecate_warn
expand_ <- function(data, dots, ...) {
lifecycle::deprecate_warn("1.0.0", "expand_()", "expand()", always = TRUE)
UseMethod("expand_")
}caller_env — a name the prelude does not declarename: caller_env
expand_.data.frame <- function(data, dots, ...) {
dots <- compat_lazy_dots(dots, caller_env())
expand(data, !!!dots)
}lifecycle::deprecate_warn — a name the prelude does not declarename: lifecycle::deprecate_warn
crossing_ <- function(x) {
lifecycle::deprecate_warn("1.0.0", "crossing_()", "crossing()", always = TRUE)
x <- compat_lazy_dots(x, caller_env())
crossing(!!!x)
}lifecycle::deprecate_warn — a name the prelude does not declarename: lifecycle::deprecate_warn
nesting_ <- function(x) {
lifecycle::deprecate_warn("1.2.0", "nesting_()", "nesting()", always = TRUE)
x <- compat_lazy_dots(x, caller_env())
nesting(!!!x)
}lifecycle::deprecate_warn — a name the prelude does not declarename: lifecycle::deprecate_warn
extract_ <- function(
data,
col,
into,
regex = "([[:alnum:]]+)",
remove = TRUE,
convert = FALSE,
...
) {
lifecycle::deprecate_warn("1.0.0", "extract_()", "extract()", always = TRUE)
UseMethod("extract_")
}caller_env — a name the prelude does not declarename: caller_env
extract_.data.frame <- function(
data,
col,
into,
regex = "([[:alnum:]]+)",
remove = TRUE,
convert = FALSE,
...
) {
col <- compat_lazy(col, caller_env())
extract(
data,
col = !!col,
into = into,
regex = regex,
remove = remove,
convert = convert,
...
)
}lifecycle::deprecate_warn — a name the prelude does not declarename: lifecycle::deprecate_warn
fill_ <- function(data, fill_cols, .direction = c("down", "up")) {
lifecycle::deprecate_warn("1.2.0", "fill_()", "fill()", always = TRUE)
UseMethod("fill_")
}syms — a name the prelude does not declarename: syms
fill_.data.frame <- function(
data,
fill_cols,
.direction = c("down", "up", "downup", "updown")
) {
vars <- syms(fill_cols)
fill(data, !!!vars, .direction = .direction)
}lifecycle::deprecate_warn — a name the prelude does not declarename: lifecycle::deprecate_warn
gather_ <- function(
data,
key_col,
value_col,
gather_cols,
na.rm = FALSE,
convert = FALSE,
factor_key = FALSE
) {
lifecycle::deprecate_warn("1.2.0", "gather_()", "gather()", always = TRUE)
UseMethod("gather_")
}Failure("Unsupported positional argument after a named one.")gather_.data.frame <- function(
data,
key_col,
value_col,
gather_cols,
na.rm = FALSE,
convert = FALSE,
factor_key = FALSE
) {
key_col <- sym(key_col)
value_col <- sym(value_col)
gather_cols <- syms(gather_cols)
gather(
data,
key = !!key_col,
value = !!value_col,
!!!gather_cols,
na.rm = na.rm,
convert = convert,
factor_key = factor_key
)
}lifecycle::deprecate_stop — a name the prelude does not declarename: lifecycle::deprecate_stop
nest_ <- function(...) {
lifecycle::deprecate_stop("1.0.0", "nest_()", "nest()", always = TRUE)
}lifecycle::deprecate_warn — a name the prelude does not declarename: lifecycle::deprecate_warn
separate_rows_ <- function(
data,
cols,
sep = "[^[:alnum:].]+",
convert = FALSE
) {
lifecycle::deprecate_warn("1.2.0", "separate_rows_()", "separate_rows()")
UseMethod("separate_rows_")
}syms — a name the prelude does not declarename: syms
separate_rows_.data.frame <- function(
data,
cols,
sep = "[^[:alnum:].]+",
convert = FALSE
) {
cols <- syms(cols)
separate_rows(data, !!!cols, sep = sep, convert = convert)
}lifecycle::deprecate_warn — a name the prelude does not declarename: lifecycle::deprecate_warn
separate_ <- function(
data,
col,
into,
sep = "[^[:alnum:]]+",
remove = TRUE,
convert = FALSE,
extra = "warn",
fill = "warn",
...
) {
lifecycle::deprecate_warn("1.2.0", "separate_()", "separate()", always = TRUE)
UseMethod("separate_")
}sym — a name the prelude does not declarename: sym
separate_.data.frame <- function(
data,
col,
into,
sep = "[^[:alnum:]]+",
remove = TRUE,
convert = FALSE,
extra = "warn",
fill = "warn",
...
) {
col <- sym(col)
separate(
data,
col = !!col,
into = into,
sep = sep,
remove = remove,
convert = convert,
extra = extra,
fill = fill,
...
)
}lifecycle::deprecate_warn — a name the prelude does not declarename: lifecycle::deprecate_warn
spread_ <- function(
data,
key_col,
value_col,
fill = NA,
convert = FALSE,
drop = TRUE,
sep = NULL
) {
lifecycle::deprecate_warn("1.2.0", "spread_()", "spread()", always = TRUE)
UseMethod("spread_")
}sym — a name the prelude does not declarename: sym
spread_.data.frame <- function(
data,
key_col,
value_col,
fill = NA,
convert = FALSE,
drop = TRUE,
sep = NULL
) {
key_col <- sym(key_col)
value_col <- sym(value_col)
spread(
data,
key = !!key_col,
value = !!value_col,
fill = fill,
convert = convert,
drop = drop,
sep = sep
)
}lifecycle::deprecate_warn — a name the prelude does not declarename: lifecycle::deprecate_warn
unite_ <- function(data, col, from, sep = "_", remove = TRUE) {
lifecycle::deprecate_warn("1.2.0", "unite_()", "unite()", always = TRUE)
UseMethod("unite_")
}caller_env — a name the prelude does not declarename: caller_env
unite_.data.frame <- function(data, col, from, sep = "_", remove = TRUE) {
col <- quo_get_expr(compat_lazy(col, caller_env()))
from <- syms(from)
unite(data, !!col, !!!from, sep = sep, remove = remove)
}lifecycle::deprecate_stop — a name the prelude does not declarename: lifecycle::deprecate_stop
unnest_ <- function(...) {
lifecycle::deprecate_stop("1.0.0", "unnest_()", "unnest()")
}NULLNULLcaller_env — a name the prelude does not declarename: caller_env
col_simplify <- function(
x,
...,
ptype = NULL,
transform = NULL,
simplify = TRUE,
error_call = caller_env()
) {
check_dots_empty()
if (!is.null(transform)) {
transform <- as_function(transform)
}
if (!vec_is_list(x)) {
if (!is.null(transform)) {
x <- transform(x)
}
if (!is.null(ptype)) {
x <- vec_cast(x, ptype, call = error_call)
}
return(x)
}
if (!is.null(transform)) {
x <- tidyr_new_list(x)
x <- map(x, transform)
# Can't convert result to list_of, as we can't be certain of element types
}
if (!is.null(ptype)) {
x <- tidyr_new_list(x)
x <- vec_cast_common(!!!x, .to = ptype, .call = error_call)
x <- new_list_of(x, ptype = ptype)
}
if (!simplify) {
return(x)
}
# Don't simplify lists of lists, because that typically indicates that
# there might be multiple values.
if (is_list_of(x)) {
has_list_of_list <- vec_is_list(list_of_ptype(x))
} else {
has_list_of_list <- any(map_lgl(x, vec_is_list))
}
if (has_list_of_list) {
return(x)
}
# Don't try and simplify non-vectors. list-of types always contain vectors.
if (is_list_of(x)) {
has_non_vector <- FALSE
} else {
has_non_vector <- !list_all_vectors2(x)
}
if (has_non_vector) {
return(x)
}
out <- tidyr_new_list(x)
ptype <- list_of_ptype(x)
sizes <- list_sizes(out)
# Ensure empty elements are filled in with their correct size 1 equivalent
info <- list_replace_null(out, sizes, ptype = ptype)
out <- info$x
sizes <- info$sizes
info <- list_replace_empty_typed(out, sizes, ptype = ptype)
out <- info$x
sizes <- info$sizes
# Don't try to simplify if there are any size >1 left at this point
has_non_scalar <- any(sizes != 1L)
if (has_non_scalar) {
return(x)
}
# Assume that if combining fails, then we want to return the object
# after the `ptype` and `transform` have been applied, but before the
# empty element filling and list attribute stripping was applied
tryCatch(
list_unchop(out, ptype = ptype),
vctrs_error_incompatible_type = function(e) x
)
}caller_env — a name the prelude does not declarename: caller_env
df_simplify <- function(
x,
...,
ptype = NULL,
transform = NULL,
simplify = TRUE,
error_call = caller_env()
) {
check_dots_empty()
ptype <- check_list_of_ptypes(ptype, names(x), call = error_call)
transform <- check_list_of_functions(transform, names(x), call = error_call)
simplify <- check_list_of_bool(simplify, names(x), call = error_call)
x_n <- length(x)
x_size <- vec_size(x)
x_names <- names(x)
out <- vector("list", length = x_n)
names(out) <- x_names
for (i in seq_len(x_n)) {
col <- x[[i]]
col_name <- x_names[[i]]
col_ptype <- ptype[[col_name]]
col_transform <- transform[[col_name]]
col_simplify <- simplify[[col_name]] %||% TRUE
out[[i]] <- col_simplify(
x = col,
ptype = col_ptype,
transform = col_transform,
simplify = col_simplify,
error_call = error_call
)
}
new_data_frame(out, n = x_size)
}caller_env — a name the prelude does not declarename: caller_env
check_pluckers <- function(..., .call = caller_env()) {
pluckers <- list2(...)
is_string <- map_lgl(pluckers, ~ is.character(.x) && length(.x) == 1)
auto_name <- names2(pluckers) == "" & is_string
if (any(auto_name)) {
names(pluckers)[auto_name] <- unlist(pluckers[auto_name])
}
check_unique_names(pluckers, arg = "...", call = .call)
# Standardize all pluckers to lists for splicing into `pluck()`
# and for easier handling in `strike()`
is_not_list <- !map_lgl(pluckers, vec_is_list)
pluckers[is_not_list] <- map(pluckers[is_not_list], vec_chop)
pluckers
}vec_is_list — a name the prelude does not declarename: vec_is_list
strike <- function(x, indices) {
if (!vec_is_list(indices)) {
cli::cli_abort("{.arg indices} must be a list.", .internal = TRUE)
}
n_indices <- vec_size(indices)
if (n_indices == 0L) {
# Edge case corresponding to an empty plucker
return(x)
}
index <- indices[[1L]]
indices <- indices[-1L]
size <- vec_size(x)
is_valid_index <-
(is.numeric(index) && (index <= size)) ||
(is.character(index) && has_name(x, index))
if (!is_valid_index) {
# Nothing to do if the `pluck()` missed entirely
return(x)
}
index <- vec_as_location(index, n = size, names = names(x))
if (n_indices == 1L) {
# At base index, remove it
x <- x[-index]
} else {
# Not at base index yet, continue recursion
x[[index]] <- strike(x[[index]], indices)
}
x
}check_data_frame — one of the package’s own names, itself untypedname: check_data_frame
hoist <- function(
.data,
.col,
...,
.remove = TRUE,
.simplify = TRUE,
.ptype = NULL,
.transform = NULL
) {
check_data_frame(.data)
check_required(.col)
pluckers <- check_pluckers(...)
check_bool(.remove)
.col <- tidyselect::vars_pull(names(.data), {{ .col }})
x <- .data[[.col]]
vec_check_list(x, arg = ".data[[.col]]")
# These are also checked in df_simplify(), but we check here to generate
# errors with argument names
check_list_of_ptypes(.ptype, names(x))
check_list_of_bool(.simplify, names(x))
check_list_of_functions(.transform, names(x))
# In R <4.1, `::` is quite slow and this is a tight loop, so eliminating
# the lookup has a large performance impact:
# https://github.com/tidyverse/tidyr/issues/1001
pluck <- purrr::pluck
cols <- map(pluckers, function(idx) {
map(x, ~ pluck(.x, !!!idx))
})
cols <- new_data_frame(cols, n = vec_size(.data))
cols <- df_simplify(
cols,
ptype = .ptype,
transform = .transform,
simplify = .simplify
)
# Place new columns before old column
out <- df_append(.data, cols, after = match(.col, names(.data)) - 1L)
if (.remove) {
x <- map(x, function(x) {
# rev() is sneaky hack assuming that most people will remove in
# numeric order, so this should avoid most order problems. A full
# resolution will be considerably more work.
for (plucker in rev(pluckers)) {
x <- strike(x, plucker)
}
x
})
if (every(x, is_empty)) {
x <- NULL
}
out[[.col]] <- x
}
reconstruct_tibble(.data, out)
}UseMethod — a name the prelude does not declarename: UseMethod
nest_legacy <- function(data, ..., .key = "data") {
UseMethod("nest_legacy")
}ensym — a name the prelude does not declarename: ensym
nest_legacy.tbl_df <- function(data, ..., .key = "data") {
key_var <- as_string(ensym(.key))
nest_vars <- unname(tidyselect::vars_select(names(data), ...))
if (is_empty(nest_vars)) {
nest_vars <- names(data)
}
if (dplyr::is_grouped_df(data)) {
group_vars <- dplyr::group_vars(data)
} else {
group_vars <- setdiff(names(data), nest_vars)
}
nest_vars <- setdiff(nest_vars, group_vars)
data <- dplyr::ungroup(data)
if (is_empty(group_vars)) {
return(tibble(!!key_var := list(data)))
}
out <- dplyr::select(data, !!!syms(group_vars))
grouped_data <- dplyr::group_by(data, !!!syms(group_vars), .drop = TRUE)
idx <- dplyr::group_indices(grouped_data)
representatives <- which(!duplicated(idx))
out <- dplyr::slice(out, representatives)
out[[key_var]] <- unname(split(data[nest_vars], idx))[unique(idx)]
out
}Failure("Unsupported argument after an ellipsis.")nest_legacy.data.frame <- function(data, ..., .key = "data") {
.key <- enquo(.key)
# Don't transform subclasses
if (identical(class(data), "data.frame")) {
data <- tibble::as_tibble(data)
}
nest_legacy.tbl_df(data, ..., .key = !!.key)
}UseMethod — a name the prelude does not declarename: UseMethod
unnest_legacy <- function(
data,
...,
.drop = NA,
.id = NULL,
.sep = NULL,
.preserve = NULL
) {
UseMethod("unnest_legacy")
}is_list — a name the prelude does not declarename: is_list
id_col <- function(x) {
stopifnot(is_list(x))
ids <- if (is_null(names(x))) seq_along(x) else names(x)
lengths <- map_int(x, length)
ids[rep(seq_along(ids), lengths)]
}is_list — a name the prelude does not declarename: is_list
enframe <- function(x, col_name, .id = NULL) {
if (!is_list(x)) {
x <- list(x)
}
col <- unname(x)
col <- list_unchop(col)
out <- set_names(list(col), col_name)
out <- as_tibble(out)
if (!is_null(.id)) {
out[[.id]] <- id_col(x)
}
out
}is.data.frame — a name the prelude does not declarename: is.data.frame
list_col_type <- function(x) {
is_data_frame <- is.data.frame(attr(x, "ptype", exact = TRUE)) ||
(is.list(x) && all(map_lgl(x, is.data.frame)))
is_atomic <- all(map_lgl(x, function(x) {
is_atomic(x) || (is_list(x) && !is.object(x))
}))
if (is_data_frame) {
"dataframe"
} else if (is_atomic) {
"atomic"
} else {
"mixed"
}
}enquo — a name the prelude does not declarename: enquo
unnest_legacy.data.frame <- function(
data,
...,
.drop = NA,
.id = NULL,
.sep = NULL,
.preserve = NULL
) {
preserve <- tidyselect::vars_select(names(data), !!enquo(.preserve))
quos <- quos(...)
if (is_empty(quos)) {
list_cols <- names(data)[map_lgl(data, is_list)]
list_cols <- setdiff(list_cols, preserve)
quos <- syms(list_cols)
}
if (length(quos) == 0) {
return(data)
}
nested <- dplyr::transmute(dplyr::ungroup(data), !!!quos)
n <- map(nested, function(x) unname(map_int(x, NROW)))
if (length(unique(n)) != 1) {
cli::cli_abort("All nested columns must have the same number of elements.")
}
types <- map_chr(nested, list_col_type)
nest_types <- split.default(nested, types)
if (length(nest_types$mixed) > 0) {
probs <- names(nest_types$mixed)
cli::cli_abort(c(
"Each column must either be a list of vectors or a list of data frames.",
i = "Problems in: {.var {probs}}"
))
}
unnested_atomic <- imap(nest_types$atomic %||% list(), enframe, .id = .id)
if (length(unnested_atomic) > 0) {
unnested_atomic <- dplyr::bind_cols(unnested_atomic)
}
unnested_dataframe <- map(nest_types$dataframe %||% list(), function(.) {
if (length(.) == 0L) {
attr(., "ptype") %||% data.frame()
} else {
dplyr::bind_rows(., .id = .id)
}
})
if (!is_null(.sep)) {
unnested_dataframe <- imap(
unnested_dataframe,
function(df, name) {
set_names(df, paste(name, names(df), sep = .sep))
}
)
}
if (length(unnested_dataframe) > 0) {
unnested_dataframe <- dplyr::bind_cols(unnested_dataframe)
}
# Keep list columns by default, only if the rows aren't expanded
if (identical(.drop, NA)) {
n_in <- nrow(data)
if (length(unnested_atomic)) {
n_out <- nrow(unnested_atomic)
} else {
n_out <- nrow(unnested_dataframe)
}
.drop <- n_out != n_in
}
if (.drop) {
is_atomic <- map_lgl(data, is_atomic)
group_vars <- names(data)[is_atomic]
} else {
group_vars <- names(data)
}
group_vars <- setdiff(group_vars, names(nested))
# Add list columns to be preserved
group_vars <- union(group_vars, preserve)
rest <- data[rep(seq_nrow(data), n[[1]]), group_vars, drop = FALSE]
out <- dplyr::bind_cols(rest, unnested_atomic, unnested_dataframe)
reconstruct_tibble(data, out)
}vec_paste0 — one of the package’s own names, itself untypedname: vec_paste0
strip_names <- function(df, base, names_sep) {
base <- vec_paste0(base, names_sep)
names <- names(df)
has_prefix <- regexpr(base, names, fixed = TRUE) == 1L
names[has_prefix] <- substr(
names[has_prefix],
nchar(base) + 1,
nchar(names[has_prefix])
)
set_names(df, names)
}current_env — a name the prelude does not declarename: current_env
pack <- function(.data, ..., .names_sep = NULL, .error_call = current_env()) {
check_data_frame(.data, call = .error_call)
cols <- enquos(...)
if (any(names2(cols) == "")) {
cli::cli_abort("All elements of `...` must be named.", call = .error_call)
}
check_string(.names_sep, allow_null = TRUE, call = .error_call)
cols <- with_indexed_errors(
map(cols, function(col) {
tidyselect::eval_select(
expr = col,
data = .data,
allow_rename = FALSE,
error_call = NULL
)
}),
message = function(cnd) {
cli::format_inline("In expression named {.arg {cnd$name}}:")
},
.error_call = .error_call
)
unpacked <- setdiff(names(.data), unlist(map(cols, names)))
unpacked <- .data[unpacked]
packed <- map(cols, ~ .data[.x])
if (!is.null(.names_sep)) {
packed <- imap(packed, strip_names, names_sep = .names_sep)
}
packed <- new_data_frame(packed, n = vec_size(.data))
out <- vec_cbind(unpacked, packed, .error_call = .error_call)
reconstruct_tibble(.data, out)
}Failure("Unsupported positional argument after a named one.")check_inner_inner_duplicate <- function(x, error_call = caller_env()) {
n <- length(x)
if (n == 0L || n == 1L) {
# Nothing to duplicate across
return(invisible())
}
outer <- names(x)
x <- unname(x)
inner <- map(x, names)
inner <- map(inner, unique)
outer <- vec_rep_each(outer, times = list_sizes(inner))
inner <- list_unchop(inner, ptype = character())
problems <- vec_duplicate_detect(inner)
if (!any(problems)) {
return(invisible())
}
outer <- vec_slice(outer, problems)
inner <- vec_slice(inner, problems)
split <- vec_split(outer, inner)
inners <- split$key
outers <- split$val
bullets <- map2_chr(inners, outers, function(inner, outer) {
cli::format_inline("{.code {inner}}, within {.code {outer}}.")
})
bullets <- set_names(bullets, "i")
bullets <- cli::format_bullets_raw(bullets)
bullets <- set_names(bullets, " ")
message <- c(
"Can't duplicate names within the affected columns.",
x = "These names are duplicated:",
bullets,
i = "Use `names_sep` to disambiguate using the column name.",
i = "Or use `names_repair` to specify a repair strategy."
)
cli::cli_abort(message, call = error_call)
}Failure("Unsupported positional argument after a named one.")check_outer_inner_duplicate <- function(x, outer, error_call = caller_env()) {
# Names of unpacked columns will disappear so aren't considered
outer <- setdiff(outer, names(x))
inner <- map(x, names)
inner <- map(inner, unique)
problems <- map(inner, function(x) intersect(x, outer))
problems <- vec_slice(problems, list_sizes(problems) != 0L)
if (length(problems) == 0L) {
return(invisible())
}
bullets <- map2_chr(problems, names(problems), function(inner, outer) {
cli::format_inline("{.code {inner}}, from {.code {outer}}.")
})
bullets <- set_names(bullets, "i")
bullets <- cli::format_bullets_raw(bullets)
bullets <- set_names(bullets, " ")
message <- c(
"Can't duplicate names between the affected columns and the original data.",
x = "These names are duplicated:",
bullets,
i = "Use `names_sep` to disambiguate using the column name.",
i = "Or use `names_repair` to specify a repair strategy."
)
cli::cli_abort(message, call = error_call)
}set_names — a name the prelude does not declarename: set_names
rename_with_names_sep <- function(x, outer, names_sep) {
inner <- names(x)
names <- apply_names_sep(outer, inner, names_sep)
set_names(x, names)
}current_env — a name the prelude does not declarename: current_env
unpack <- function(
data,
cols,
...,
names_sep = NULL,
names_repair = "check_unique",
error_call = current_env()
) {
check_dots_empty0(...)
check_data_frame(data, call = error_call)
check_required(cols, call = error_call)
check_string(names_sep, allow_null = TRUE, call = error_call)
# Start from first principles to avoid issues in any subclass methods
out <- tidyr_new_list(data)
cols <- tidyselect::eval_select(
expr = enquo(cols),
data = data,
allow_rename = FALSE,
error_call = error_call
)
cols <- out[cols]
cols <- cols[map_lgl(cols, is.data.frame)]
cols_names <- names(cols)
if (is.null(names_sep) && is_string(names_repair, "check_unique")) {
# Only perform checks if user hasn't supplied `names_sep` or `names_repair`.
# We let `vec_as_names()` catch any remaining problems.
check_inner_inner_duplicate(cols, error_call = error_call)
check_outer_inner_duplicate(cols, names(data), error_call = error_call)
}
if (!is.null(names_sep)) {
out[cols_names] <- map2(
cols,
cols_names,
rename_with_names_sep,
names_sep = names_sep
)
}
# Signal to tell `df_list()` to unpack
names <- names(out)
names[names %in% cols_names] <- ""
names(out) <- names
size <- vec_size(data)
out <- df_list(!!!out, .size = size, .name_repair = "minimal")
out <- tibble::new_tibble(out, nrow = size)
names(out) <- vec_as_names(
names = names(out),
repair = names_repair,
repair_arg = "names_repair",
call = error_call
)
reconstruct_tibble(data, out)
}maybe_missing — a name the prelude does not declarename: maybe_missing
is_default_key <- function(key) {
if (identical(maybe_missing(key), deprecated())) {
# Temporary support for S3 method authors that set `.key = deprecated()`.
# Remove this entire helper all methods have been updated.
key <- NULL
}
is.null(key)
}caller_env — a name the prelude does not declarename: caller_env
check_key <- function(key, error_call = caller_env()) {
if (is_default_key(key)) {
"data"
} else {
check_string(key, allow_empty = FALSE, arg = ".key", call = error_call)
key
}
}enquos — a name the prelude does not declarename: enquos
nest <- function(.data, ..., .by = NULL, .key = NULL, .names_sep = NULL) {
cols <- enquos(...)
empty <- names2(cols) == ""
if (any(empty)) {
cols_good <- cols[!empty]
cols_bad <- cols[empty]
.key <- check_key(.key)
if (length(cols_bad) == 1L) {
cols_bad <- cols_bad[[1]]
cols_fixed_expr <- expr(!!cols_bad)
} else {
cols_fixed_expr <- expr(c(!!!cols_bad))
}
cols_fixed_label <- as_label(cols_fixed_expr)
cols_fixed <- quos(!!.key := !!cols_fixed_expr)
cols <- c(cols_good, cols_fixed)
lifecycle::deprecate_warn(
when = "1.0.0",
what = I("Supplying `...` without names"),
details = c(
i = "Please specify a name for each selection.",
i = cli::format_inline("Did you want `{(.key)} = {cols_fixed_label}`?")
),
always = TRUE
)
return(nest(.data, !!!cols, .by = {{ .by }}))
}
UseMethod("nest")
}caller_env — a name the prelude does not declarename: caller_env
warn_unused_key <- function(error_call = caller_env()) {
message <- c(
"Can't supply both {.arg .key} and {.arg ...}.",
i = "{.arg .key} will be ignored."
)
cli::cli_warn(message, call = error_call)
}caller_env — a name the prelude does not declarename: caller_env
nest_info <- function(
.data,
...,
.by = NULL,
.key = NULL,
.error_call = caller_env()
) {
by <- enquo(.by)
cols <- enquos(...)
n_cols <- length(cols)
key <- check_key(.key, error_call = .error_call)
if (n_cols != 0L && !is_default_key(.key)) {
warn_unused_key(error_call = .error_call)
}
cols <- with_indexed_errors(
map(cols, function(col) {
names(tidyselect::eval_select(
expr = col,
data = .data,
allow_rename = FALSE,
error_call = NULL
))
}),
message = function(cnd) {
cli::format_inline("In expression named {.arg {cnd$name}}:")
},
.error_call = .error_call
)
names <- names(.data)
outer <- names(tidyselect::eval_select(
expr = by,
data = .data,
allow_rename = FALSE,
error_call = .error_call
))
inner <- list_unchop(cols, ptype = character(), name_spec = zap())
inner <- vec_unique(inner)
if (n_cols == 0L) {
# Derive `inner` names from `.by`
inner <- setdiff(names, outer)
cols <- list2(!!key := inner)
}
if (quo_is_null(by)) {
# Derive `outer` names from `...`
outer <- setdiff(names, inner)
}
# Regenerate quosures for `pack()`
cols <- map(cols, function(col) {
quo(all_of(!!col))
})
cols <- new_quosures(cols)
list(
cols = cols,
inner = inner,
outer = outer
)
}Failure("Unsupported argument after an ellipsis.")nest.tbl_df <- function(
.data,
...,
.by = NULL,
.key = NULL,
.names_sep = NULL
) {
error_call <- current_env()
info <- nest_info(.data, ..., .by = {{ .by }}, .key = .key)
cols <- info$cols
inner <- info$inner
outer <- info$outer
inner <- .data[inner]
inner <- pack(
inner,
!!!cols,
.names_sep = .names_sep,
.error_call = error_call
)
out <- .data[outer]
out <- vec_cbind(
out,
inner,
.name_repair = "check_unique",
.error_call = error_call
)
out <- reconstruct_tibble(.data, out)
out <- chop(out, cols = all_of(names(cols)), error_call = error_call)
# `nest()` currently doesn't return list-of columns
for (name in names(cols)) {
out[[name]] <- tidyr_new_list(out[[name]])
}
out
}Failure("Unsupported argument after an ellipsis.")nest.data.frame <- function(
.data,
...,
.by = NULL,
.key = NULL,
.names_sep = NULL
) {
# The data frame print handles nested data frames poorly, so we want to
# convert data frames (but not subclasses) to tibbles
if (identical(class(.data), "data.frame")) {
.data <- as_tibble(.data)
}
nest.tbl_df(
.data,
...,
.by = {{ .by }},
.key = .key,
.names_sep = .names_sep
)
}Failure("Unsupported argument after an ellipsis.")nest.grouped_df <- function(
.data,
...,
.by = NULL,
.key = NULL,
.names_sep = NULL
) {
by <- enquo(.by)
if (!quo_is_null(by)) {
cli::cli_abort(
"Can't supply {.arg .by} when {.arg .data} is a grouped data frame."
)
}
if (missing(...)) {
.key <- check_key(.key)
cols <- setdiff(names(.data), dplyr::group_vars(.data))
nest.tbl_df(.data, !!.key := all_of(cols), .names_sep = .names_sep)
} else {
nest.tbl_df(.data, ..., .key = .key, .names_sep = .names_sep)
}
}caller_env — a name the prelude does not declarename: caller_env
check_pivot_spec <- function(spec, call = caller_env()) {
check_data_frame(spec, call = call)
if (!has_name(spec, ".name") || !has_name(spec, ".value")) {
cli::cli_abort(
"{.arg spec} must have {.var .name} and {.var .value} columns.",
call = call
)
}
check_character(spec$.name, call = call)
if (vec_duplicate_any(spec$.name)) {
cli::cli_abort("{.var spec$.name} must be unique.", call = call)
}
check_character(spec$.value, call = call)
# Ensure `.name` and `.value` come first, in that order
vars <- union(c(".name", ".value"), names(spec))
spec <- spec[vars]
spec
}cnd_signal — a name the prelude does not declarename: cnd_signal
wrap_error_names <- function(code) {
withCallingHandlers(
code,
vctrs_error_names = function(cnd) {
cnd$arg <- "names_repair"
cnd_signal(cnd)
}
)
}check_dots_used — a name the prelude does not declarename: check_dots_used
pivot_longer <- function(
data,
cols,
...,
cols_vary = "fastest",
names_to = "name",
names_prefix = NULL,
names_sep = NULL,
names_pattern = NULL,
names_ptypes = NULL,
names_transform = NULL,
names_repair = "check_unique",
values_to = "value",
values_drop_na = FALSE,
values_ptypes = NULL,
values_transform = NULL
) {
check_dots_used()
UseMethod("pivot_longer")
}current_env — a name the prelude does not declarename: current_env
build_longer_spec <- function(
data,
cols,
...,
names_to = "name",
values_to = "value",
names_prefix = NULL,
names_sep = NULL,
names_pattern = NULL,
names_ptypes = NULL,
names_transform = NULL,
error_call = current_env()
) {
check_dots_empty0(...)
check_data_frame(data, call = error_call)
check_required(cols, call = error_call)
check_character(names_to, allow_null = TRUE, call = error_call)
cols <- tidyselect::eval_select(
expr = enquo(cols),
data = data[unique(names(data))],
allow_rename = FALSE,
error_call = error_call
)
cols <- names(cols)
if (length(cols) == 0) {
cli::cli_abort(
"{.arg cols} must select at least one column.",
call = error_call
)
}
if (is.null(names_prefix)) {
names <- cols
} else {
names <- gsub(vec_paste0("^", names_prefix), "", cols)
}
if (is.null(names_to)) {
names_to <- character(0L)
}
n_names_to <- length(names_to)
has_names_sep <- !is.null(names_sep)
has_names_pattern <- !is.null(names_pattern)
if (n_names_to == 0L) {
names <- tibble::new_tibble(x = list(), nrow = length(names))
} else if (n_names_to == 1L) {
if (has_names_sep) {
cli::cli_abort(
"{.arg names_sep} can't be used with a length 1 {.arg names_to}.",
call = error_call
)
}
if (has_names_pattern) {
names <- str_extract(
names,
names_to,
regex = names_pattern,
error_call = error_call
)[[1]]
}
names <- tibble(!!names_to := names)
} else {
if (!xor(has_names_sep, has_names_pattern)) {
cli::cli_abort(
paste0(
"If you supply multiple names in {.arg names_to} you must also supply one",
" of {.arg names_sep} or {.arg names_pattern}."
),
call = error_call
)
}
if (has_names_sep) {
names <- str_separate(
names,
names_to,
sep = names_sep,
error_call = error_call
)
} else {
names <- str_extract(
names,
names_to,
regex = names_pattern,
error_call = error_call
)
}
}
if (".value" %in% names_to) {
values_to <- NULL
} else {
vec_assert(values_to, ptype = character(), size = 1, call = error_call)
}
names_ptypes <- check_list_of_ptypes(
names_ptypes,
names(names),
call = error_call
)
names_transform <- check_list_of_functions(
names_transform,
names(names),
call = error_call
)
# Optionally, transform cols
for (col in names(names_transform)) {
f <- names_transform[[col]]
names[[col]] <- f(names[[col]])
}
# Optionally, cast variables generated from columns
for (col in names(names_ptypes)) {
ptype <- names_ptypes[[col]]
names[[col]] <- vec_cast(
names[[col]],
ptype,
x_arg = col,
call = error_call
)
}
out <- tibble(.name = cols)
out[[".value"]] <- values_to
out <- vec_cbind(out, names)
out
}vec_duplicate_any — a name the prelude does not declarename: vec_duplicate_any
deduplicate_spec <- function(spec, df) {
# Ensure each .name has a unique output identifier
key <- spec[setdiff(names(spec), ".name")]
if (vec_duplicate_any(key)) {
pos <- vec_group_loc(key)$loc
seq <- vector("integer", length = nrow(spec))
for (i in seq_along(pos)) {
seq[pos[[i]]] <- seq_along(pos[[i]])
}
spec$.seq <- seq
}
# Match spec to data, handling duplicated column names
col_id <- vec_match(names(df), spec$.name)
has_match <- !is.na(col_id)
if (!vec_duplicate_any(col_id[has_match])) {
return(spec)
}
spec <- vec_slice(spec, col_id[has_match])
# Need to use numeric indices because names only match first
spec$.name <- seq_along(df)[has_match]
pieces <- vec_split(seq_len(nrow(spec)), col_id[has_match])
copy <- integer(nrow(spec))
for (i in seq_along(pieces$val)) {
idx <- pieces$val[[i]]
copy[idx] <- seq_along(idx)
}
spec$.seq <- copy
spec
}drop_cols <- function(df, cols) {
if (is.character(cols)) {
df[setdiff(names(df), cols)]
} else if (is.integer(cols)) {
df[-cols]
} else {
cli::cli_abort("Invalid input", .internal = TRUE)
}
}current_env — a name the prelude does not declarename: current_env
pivot_longer_spec <- function(
data,
spec,
...,
cols_vary = "fastest",
names_repair = "check_unique",
values_drop_na = FALSE,
values_ptypes = NULL,
values_transform = NULL,
error_call = current_env()
) {
check_dots_empty0(...)
spec <- check_pivot_spec(spec, call = error_call)
spec <- deduplicate_spec(spec, data)
cols_vary <- arg_match0(
arg = cols_vary,
values = c("fastest", "slowest"),
error_call = error_call
)
# Quick hack to ensure that split() preserves order
v_fct <- factor(spec$.value, levels = unique(spec$.value))
values <- split(spec$.name, v_fct)
value_names <- names(values)
value_keys <- split(spec[-(1:2)], v_fct)
keys <- vec_unique(spec[-(1:2)])
values_ptypes <- check_list_of_ptypes(
values_ptypes,
value_names,
call = error_call
)
values_transform <- check_list_of_functions(
values_transform,
value_names,
call = error_call
)
vals <- set_names(vec_init(list(), length(values)), value_names)
for (value in value_names) {
cols <- values[[value]]
col_id <- vec_match(value_keys[[value]], keys)
n_val_cols <- nrow(keys)
val_cols <- vec_init(list(), n_val_cols)
val_cols[col_id] <- unname(as.list(data[cols]))
val_cols[-col_id] <- list(rep(NA, nrow(data)))
if (has_name(values_transform, value)) {
val_cols <- map(val_cols, values_transform[[value]])
}
# Name inputs that came from `data`, just for good error messages when
# taking the common type and casting
names <- vec_rep("", times = n_val_cols)
names[col_id] <- cols
names(val_cols) <- names
val_type <- vec_ptype_common(
!!!val_cols[col_id],
.ptype = values_ptypes[[value]],
.call = error_call
)
val_cols <- vec_cast_common(
!!!val_cols,
.to = val_type,
.call = error_call
)
val_cols <- unname(val_cols)
if (cols_vary == "slowest") {
vals[[value]] <- list_unchop(val_cols, ptype = val_type)
} else if (cols_vary == "fastest") {
vals[[value]] <- vec_interleave(!!!val_cols, .ptype = val_type)
} else {
cli::cli_abort("Unknown {.arg cols_vary} value.", .internal = TRUE)
}
}
vals <- as_tibble(vals)
# Join together data, keys, and vals to produce final tibble
data_cols <- drop_cols(as_tibble(data, .name_repair = "minimal"), spec$.name)
times_keys <- vec_size(data_cols)
times_data_cols <- vec_size(keys)
if (cols_vary == "slowest") {
data_cols <- vec_rep(data_cols, times_data_cols)
keys <- vec_rep_each(keys, times_keys)
} else if (cols_vary == "fastest") {
data_cols <- vec_rep_each(data_cols, times_data_cols)
keys <- vec_rep(keys, times_keys)
} else {
cli::cli_abort("Unknown {.arg cols_vary} value.", .internal = TRUE)
}
out <- wrap_error_names(vec_cbind(
data_cols,
keys,
vals,
.name_repair = names_repair,
.error_call = error_call
))
if (values_drop_na && vec_any_missing(vals)) {
out <- vec_slice(out, !vec_detect_missing(vals))
}
out$.seq <- NULL
reconstruct_tibble(data, out)
}current_env — a name the prelude does not declarename: current_env
pivot_longer.data.frame <- function(
data,
cols,
...,
cols_vary = "fastest",
names_to = "name",
names_prefix = NULL,
names_sep = NULL,
names_pattern = NULL,
names_ptypes = NULL,
names_transform = NULL,
names_repair = "check_unique",
values_to = "value",
values_drop_na = FALSE,
values_ptypes = NULL,
values_transform = NULL
) {
spec <- build_longer_spec(
data = data,
cols = {{ cols }},
names_to = names_to,
values_to = values_to,
names_prefix = names_prefix,
names_sep = names_sep,
names_pattern = names_pattern,
names_ptypes = names_ptypes,
names_transform = names_transform,
error_call = current_env()
)
pivot_longer_spec(
data = data,
spec = spec,
cols_vary = cols_vary,
names_repair = names_repair,
values_drop_na = values_drop_na,
values_ptypes = values_ptypes,
values_transform = values_transform,
error_call = current_env()
)
}name — a name the prelude does not declarename: name
pivot_wider <- function(
data,
...,
id_cols = NULL,
id_expand = FALSE,
names_from = name,
names_prefix = "",
names_sep = "_",
names_glue = NULL,
names_sort = FALSE,
names_vary = "fastest",
names_expand = FALSE,
names_repair = "check_unique",
values_from = value,
values_fill = NULL,
values_fn = NULL,
unused_fn = NULL
) {
# TODO: Use `check_dots_used()` after removing the `id_cols` compat behavior
UseMethod("pivot_wider")
}cli::cli_abort — a name the prelude does not declarename: cli::cli_abort
stop_id_cols_oob <- function(i, arg, call) {
cli::cli_abort(
c(
"`id_cols` can't select a column already selected by `{arg}`.",
i = "Column `{i}` has already been selected."
),
parent = NA,
call = call
)
}is_string — a name the prelude does not declarename: is_string
rethrow_id_cols_oob <- function(cnd, names_from_cols, values_from_cols, call) {
i <- cnd[["i"]]
if (is_string(i)) {
# Try to throw our custom error
if (i %in% names_from_cols) {
stop_id_cols_oob(i, "names_from", call = call)
} else if (i %in% values_from_cols) {
stop_id_cols_oob(i, "values_from", call = call)
}
}
# Otherwise fall through and throw standard tidyselect error
zap()
}caller_env — a name the prelude does not declarename: caller_env
select_wider_id_cols <- function(
data,
id_cols = NULL,
names_from_cols = character(),
values_from_cols = character(),
error_call = caller_env()
) {
id_cols <- enquo(id_cols)
# Remove known non-id-cols so they are never selected
data <- data[setdiff(names(data), c(names_from_cols, values_from_cols))]
if (quo_is_null(id_cols)) {
# Default selects everything in `data` after non-id-cols have been removed
return(names(data))
}
try_fetch(
id_cols <- tidyselect::eval_select(
enquo(id_cols),
data,
allow_rename = FALSE,
error_call = error_call
),
vctrs_error_subscript_oob = function(cnd) {
rethrow_id_cols_oob(cnd, names_from_cols, values_from_cols, error_call)
}
)
names(id_cols)
}name — a name the prelude does not declarename: name
build_wider_id_cols_expr <- function(
data,
id_cols = NULL,
names_from = name,
values_from = value,
error_call = caller_env()
) {
names_from <- tidyselect::eval_select(
enquo(names_from),
data,
allow_rename = FALSE,
error_call = error_call
)
values_from <- tidyselect::eval_select(
enquo(values_from),
data,
allow_rename = FALSE,
error_call = error_call
)
out <- select_wider_id_cols(
data = data,
id_cols = {{ id_cols }},
names_from_cols = names(names_from),
values_from_cols = names(values_from),
error_call = error_call
)
expr(c(!!!out))
}name — a name the prelude does not declarename: name
build_wider_spec <- function(
data,
...,
names_from = name,
values_from = value,
names_prefix = "",
names_sep = "_",
names_glue = NULL,
names_sort = FALSE,
names_vary = "fastest",
names_expand = FALSE,
error_call = current_env()
) {
check_dots_empty0(...)
names_from <- tidyselect::eval_select(
enquo(names_from),
data,
allow_rename = FALSE,
allow_empty = FALSE,
error_call = error_call
)
values_from <- tidyselect::eval_select(
enquo(values_from),
data,
allow_rename = FALSE,
allow_empty = FALSE,
error_call = error_call
)
check_string(names_prefix, call = error_call)
check_string(names_sep, call = error_call)
check_string(names_glue, allow_null = TRUE, call = error_call)
check_bool(names_sort, call = error_call)
check_bool(names_expand, call = error_call)
names_vary <- arg_match0(
arg = names_vary,
values = c("fastest", "slowest"),
arg_nm = "names_vary",
error_call = error_call
)
data <- as_tibble(data)
data <- data[names_from]
if (names_expand) {
# `expand()` always does sort + unique
row_ids <- expand(data, !!!syms(names(data)))
} else {
row_ids <- vec_unique(data)
if (names_sort) {
row_ids <- vec_sort(row_ids)
}
}
row_names <- exec(paste, !!!row_ids, sep = names_sep)
out <- tibble(
.name = vec_paste0(names_prefix, row_names)
)
if (length(values_from) == 1) {
out$.value <- names(values_from)
} else {
if (names_vary == "fastest") {
out <- vec_rep(out, vec_size(values_from))
out$.value <- vec_rep_each(names(values_from), vec_size(row_ids))
row_ids <- vec_rep(row_ids, vec_size(values_from))
} else {
out <- vec_rep_each(out, vec_size(values_from))
out$.value <- vec_rep(names(values_from), vec_size(row_ids))
row_ids <- vec_rep_each(row_ids, vec_size(values_from))
}
out$.name <- vec_paste0(out$.value, names_sep, out$.name)
}
out <- vec_cbind(out, as_tibble(row_ids), .name_repair = "minimal")
if (!is.null(names_glue)) {
out$.name <- as.character(glue::glue_data(out, names_glue))
}
out
}caller_env — a name the prelude does not declarename: caller_env
warn_deprecated_unnamed_id_cols <- function(id_cols, user_env = caller_env(2)) {
id_cols <- as_label(id_cols)
lifecycle::deprecate_warn(
when = "1.3.0",
what = I(cli::format_inline(
"Specifying the {.arg id_cols} argument by position"
)),
details = cli::format_inline(
"Please explicitly name {.arg id_cols}, like {.code id_cols = {id_cols}}."
),
always = TRUE,
user_env = user_env
)
}Failure("Unsupported argument after an ellipsis.")compat_id_cols <- function(
id_cols,
...,
fn_call,
error_call = caller_env(),
user_env = caller_env(2)
) {
dots <- enquos(...)
# If `id_cols` is specified by name by the user, it will show up in the call.
# Otherwise, default args don't show up in the call so it won't be there.
user_specified_id_cols <- "id_cols" %in% names(fn_call)
# For compatibility (#1353), assign the first value of `...` to `id_cols` if:
# - The user didn't specify `id_cols`.
# - There is exactly 1 unnamed element in `...`.
use_compat_id_cols <-
!user_specified_id_cols &&
length(dots) == 1L &&
!is_named(dots)
if (use_compat_id_cols) {
id_cols <- dots[[1L]]
warn_deprecated_unnamed_id_cols(id_cols, user_env = user_env)
} else {
id_cols <- enquo(id_cols)
check_dots_empty0(..., call = error_call)
}
id_cols
}make.names — a name the prelude does not declarename: make.names
backtick_if_not_syntactic <- function(x) {
ok <- make.names(x) == x
ok[is.na(x)] <- FALSE
x[!ok] <- glue::backtick(x[!ok])
x
}vec_size — a name the prelude does not declarename: vec_size
chop_rectangular_df <- function(x, names) {
n_col <- vec_size(names)
n_row <- vec_size(x) / n_col
indices <- vector("list", n_col)
start <- 1L
stop <- n_row
for (i in seq_len(n_col)) {
indices[[i]] <- seq2(start, stop)
start <- start + n_row
stop <- stop + n_row
}
out <- vec_chop(x, indices)
names(out) <- names
tibble::new_tibble(out, nrow = n_row)
}| parameter | change | call | returned |
|---|---|---|---|
| x | kind:list | is_scalar(list()) | ff<> with { } |
is_scalar <- function(x) {
if (is.null(x)) {
return(FALSE)
}
if (vec_is_list(x)) {
(vec_size(x) == 1) && !have_name(x)
} else {
vec_size(x) == 1
}
}caller_env — a name the prelude does not declarename: caller_env
value_summarize <- function(
value,
value_locs,
value_name,
fn,
fn_name,
error_call = caller_env()
) {
value <- vec_chop(value, value_locs)
if (identical(fn, list)) {
# The no-op case, for performance
return(value)
}
value <- map(value, fn)
sizes <- list_sizes(value)
invalid_sizes <- sizes != 1L
if (any(invalid_sizes)) {
size <- sizes[invalid_sizes][[1]]
cli::cli_abort(
c(
"Applying {.arg {fn_name}} to {.var {value_name}} must result in a single summary value per key.",
i = "Applying {.arg {fn_name}} resulted in a vector of length {size}."
),
call = error_call
)
}
value <- list_unchop(value)
value
}current_env — a name the prelude does not declarename: current_env
pivot_wider_spec <- function(
data,
spec,
...,
names_repair = "check_unique",
id_cols = NULL,
id_expand = FALSE,
values_fill = NULL,
values_fn = NULL,
unused_fn = NULL,
error_call = current_env()
) {
check_dots_empty0(...)
check_data_frame(data, call = error_call)
spec <- check_pivot_spec(spec, call = error_call)
check_bool(id_expand, call = error_call)
names_from_cols <- names(spec)[-(1:2)]
values_from_cols <- vec_unique(spec$.value)
id_cols <- select_wider_id_cols(
data = data,
id_cols = {{ id_cols }},
names_from_cols = names_from_cols,
values_from_cols = values_from_cols,
error_call = error_call
)
values_fn <- check_list_of_functions(
values_fn,
values_from_cols,
call = error_call
)
unused_cols <- setdiff(
names(data),
c(id_cols, names_from_cols, values_from_cols)
)
unused_fn <- check_list_of_functions(
unused_fn,
unused_cols,
call = error_call
)
unused_cols <- names(unused_fn)
if (is.null(values_fill)) {
values_fill <- list()
} else if (is_scalar(values_fill)) {
values_fill <- rep_named(values_from_cols, list(values_fill))
} else if (!vec_is_list(values_fill)) {
cli::cli_abort(
"{.arg values_fill} must be {.code NULL}, a scalar, or a named list, not {.obj_type_friendly {values_fill}}.",
call = error_call
)
}
values_fill <- values_fill[intersect(names(values_fill), values_from_cols)]
input <- data
# Early conversion to tibble because data.table returns zero rows if
# zero cols are selected. Also want to avoid the grouped-df behavior
# of `complete()`.
data <- as_tibble(data)
data <- data[vec_unique(c(
id_cols,
names_from_cols,
values_from_cols,
unused_cols
))]
if (id_expand) {
data <- complete(
data,
!!!syms(id_cols),
fill = values_fill,
explicit = FALSE
)
}
# Figure out rows in output
rows <- data[id_cols]
row_id <- vec_group_id(rows)
nrow <- attr(row_id, "n")
rows <- vec_slice(rows, vec_unique_loc(row_id))
n_unused_fn <- length(unused_fn)
unused <- vector("list", length = n_unused_fn)
names(unused) <- unused_cols
if (n_unused_fn > 0L) {
# This can be expensive, only compute if we are using `unused_fn`
unused_locs <- vec_group_loc(row_id)$loc
}
for (i in seq_len(n_unused_fn)) {
unused_col <- unused_cols[[i]]
unused_fn_i <- unused_fn[[i]]
unused_value <- data[[unused_col]]
unused[[i]] <- value_summarize(
value = unused_value,
value_locs = unused_locs,
value_name = unused_col,
fn = unused_fn_i,
fn_name = "unused_fn",
error_call = error_call
)
}
unused <- tibble::new_tibble(unused, nrow = nrow)
duplicate_names <- character(0L)
value_specs <- unname(split(spec, spec$.value))
value_out <- vec_init(list(), length(value_specs))
for (i in seq_along(value_out)) {
value_spec <- value_specs[[i]]
value_name <- value_spec$.value[[1]]
value <- data[[value_name]]
cols <- data[names(value_spec)[-(1:2)]]
col_id <- vec_match(as_tibble(cols), value_spec[-(1:2)])
value_id <- data.frame(row = row_id, col = col_id)
value_fn <- values_fn[[value_name]]
if (is.null(value_fn) && vec_duplicate_any(value_id)) {
# There are unhandled duplicates. Handle them with `list()` and warn.
value_fn <- list
duplicate_names <- c(duplicate_names, value_name)
}
if (!is.null(value_fn)) {
result <- vec_group_loc(value_id)
value_id <- result$key
value_locs <- result$loc
value <- value_summarize(
value = value,
value_locs = value_locs,
value_name = value_name,
fn = value_fn,
fn_name = "values_fn",
error_call = error_call
)
}
ncol <- nrow(value_spec)
fill <- values_fill[[value_name]]
if (is.null(fill)) {
out <- vec_init(value, nrow * ncol)
} else {
stopifnot(vec_size(fill) == 1)
fill <- vec_cast(fill, value, call = error_call)
out <- vec_rep_each(fill, nrow * ncol)
}
out <- vec_assign(out, value_id$row + nrow * (value_id$col - 1L), value)
value_out[[i]] <- chop_rectangular_df(out, value_spec$.name)
}
if (length(duplicate_names) > 0L) {
duplicate_names <- glue::backtick(duplicate_names)
duplicate_names <- glue::glue_collapse(
duplicate_names,
sep = ", ",
last = " and "
)
group_cols <- c(id_cols, names_from_cols)
group_cols <- backtick_if_not_syntactic(group_cols)
group_cols <- glue::glue_collapse(group_cols, sep = ", ")
cli::cli_warn(c(
"Values from {duplicate_names} are not uniquely identified; output will contain list-cols.",
"*" = "Use `values_fn = list` to suppress this warning.",
"*" = "Use `values_fn = {{summary_fun}}` to summarise duplicates.",
"*" = "Use the following dplyr code to identify duplicates.",
" " = " {{data}} |>",
" " = " dplyr::summarise(n = dplyr::n(), .by = c({group_cols})) |>",
" " = " dplyr::filter(n > 1L)"
))
}
# `check_pivot_spec()` ensures `.name` is unique. Name repair shouldn't be needed.
values <- vec_cbind(!!!value_out, .name_repair = "minimal")
# Recreate desired column order of the new spec columns (#569)
values <- values[spec$.name]
out <- wrap_error_names(vec_cbind(
rows,
values,
unused,
.name_repair = names_repair,
.error_call = error_call
))Failure("Unsupported argument after an ellipsis.")pivot_wider.data.frame <- function(
data,
...,
id_cols = NULL,
id_expand = FALSE,
names_from = name,
names_prefix = "",
names_sep = "_",
names_glue = NULL,
names_sort = FALSE,
names_vary = "fastest",
names_expand = FALSE,
names_repair = "check_unique",
values_from = value,
values_fill = NULL,
values_fn = NULL,
unused_fn = NULL
) {
names_from <- enquo(names_from)
values_from <- enquo(values_from)
spec <- build_wider_spec(
data = data,
names_from = !!names_from,
values_from = !!values_from,
names_prefix = names_prefix,
names_sep = names_sep,
names_glue = names_glue,
names_sort = names_sort,
names_vary = names_vary,
names_expand = names_expand,
error_call = current_env()
)
id_cols <- compat_id_cols(
id_cols = {{ id_cols }},
...,
fn_call = match.call(expand.dots = FALSE)
)
id_cols <- build_wider_id_cols_expr(
data = data,
id_cols = !!id_cols,
names_from = !!names_from,
values_from = !!values_from
)
pivot_wider_spec(
data = data,
spec = spec,
id_cols = !!id_cols,
id_expand = id_expand,
names_repair = names_repair,
values_fill = values_fill,
values_fn = values_fn,
unused_fn = unused_fn,
error_call = current_env()
)
}caller_env — a name the prelude does not declarename: caller_env
map_unchop <- function(
data,
cols,
fun,
...,
.keep_empty = FALSE,
.error_call = caller_env()
) {
cols <- tidyselect::eval_select(
enquo(cols),
data = data,
allow_rename = FALSE,
allow_empty = FALSE,
error_call = .error_call
)
col_names <- names(cols)
for (col in col_names) {
data[[col]] <- fun(data[[col]], ...)
}
unchop(
data = data,
cols = all_of(col_names),
keep_empty = .keep_empty,
ptype = character(),
error_call = .error_call
)
}check_installed — a name the prelude does not declarename: check_installed
separate_longer_delim <- function(data, cols, delim, ...) {
check_installed("stringr")
check_data_frame(data)
check_required(cols)
check_string(delim)
check_dots_empty()
if (is_bare_string(delim)) {
delim <- stringr::fixed(delim)
}
map_unchop(data, {{ cols }}, stringr::str_split, pattern = delim)
}stringr::str_length — a name the prelude does not declarename: stringr::str_length
str_split_length <- function(x, width = 1) {
if (length(x) == 0L) {
return(list())
}
max_length <- max(stringr::str_length(x))
idx <- seq(1, max_length, by = width)
pieces <- stringr::str_sub_all(x, cbind(idx, length = width))
pieces <- map(pieces, function(x) x[x != ""])
pieces
}check_installed — a name the prelude does not declarename: check_installed
separate_longer_position <- function(
data,
cols,
width,
...,
keep_empty = FALSE
) {
check_installed("stringr")
check_data_frame(data)
check_required(cols)
check_number_whole(width, min = 1)
check_dots_empty()
map_unchop(
data,
{{ cols }},
str_split_length,
width = width,
.keep_empty = keep_empty
)
}caller_env — a name the prelude does not declarename: caller_env
map_unpack <- function(
data,
cols,
fun,
names_sep,
names_repair,
error_call = caller_env()
) {
cols <- tidyselect::eval_select(
enquo(cols),
data = data,
allow_rename = FALSE,
allow_empty = FALSE,
error_call = error_call
)
col_names <- names(cols)
for (col in col_names) {
data[[col]] <- fun(data[[col]], col)
}
unpack(
data = data,
cols = all_of(col_names),
names_sep = names_sep,
names_repair = names_repair,
error_call = error_call
)
}File "Rsem/lang/PAst.ml", line 210, characters 14-20: Assertion failed
check_df_alignment <- function(
col,
p,
type,
sizes,
too_few,
too_many,
advice_short = NULL,
advice_long = NULL,
call = caller_env()
) {
n_short <- sum(sizes < p, na.rm = TRUE)
n_long <- sum(sizes > p, na.rm = TRUE)
error_short <- too_few == "error" && n_short > 0
error_long <- too_many == "error" && n_long > 0
if (!error_short && !error_long) {
return()
}
cli::cli_abort(
c(
"Expected {p} {type} in each element of {.var {col}}.",
"!" = if (error_short) "{n_short} value{?s} {?was/were} too short.",
if (error_short) advice_short,
"!" = if (error_long) "{n_long} value{?s} {?was/were} too long.",
if (error_long) advice_long
),
call = call
)
}| call | verdict | error |
|---|---|---|
| debug_name(NULL, NULL, function(...) list()) | error_type | base::paste0: cannot coerce type 'closure' to vector of type 'character' |
| debug_name("col" = new.env(), "names_sep" = new.env(), "var" = local({ p <- unserialize(serialize(new("externalptr"), NULL)); attributes(p) <- NULL; p })) | error_type | base::paste0: environments cannot be coerced to other types |
| debug_name(NULL, "names_sep" = NULL, "var" = local({ p <- unserialize(serialize(new("externalptr"), NULL)); attributes(p) <- NULL; p })) | error_type | base::paste0: cannot coerce type 'externalptr' to vector of type 'character' |
| debug_name(new.env(), local({ p <- unserialize(serialize(new("externalptr"), NULL)); attributes(p) <- NULL; p }), "var" = quote(f(x))) | error_type | base::paste0: environments cannot be coerced to other types |
debug_name <- function(col, names_sep, var) {
paste0(col, names_sep %||% "_", var)
}list_sizes — a name the prelude does not declarename: list_sizes
df_align_transpose <- function(x, p, align_direction = "start") {
sizes <- list_sizes(x)
# Find the start location of each piece
starts <- cumsum(c(1L, sizes[-length(sizes)]))
# Combine all pieces sequentially, zapping names for performance.
x <- list_unchop(x, ptype = character(), name_spec = zap())
indices <- vector("list", p)
if (align_direction == "start") {
# General idea is to use the `starts` to slice with, replacing them with
# `NA` when we are too short, and then advancing the `starts` by 1 at each
# iteration.
for (i in seq_len(p)) {
small <- sizes < i
index <- starts
index[small] <- NA_integer_
indices[[i]] <- index
starts <- starts + 1L
}
} else {
# `"end"` is a little tricky because we have to hold the start
# location constant if we couldn't use it because the piece was too small.
# Pieces that are too large are automatically ignored.
gap <- sizes - p
for (i in seq_len(p)) {
small <- gap < 0
not_small <- !small
index <- starts
index[small] <- NA_integer_
indices[[i]] <- index
starts[not_small] <- starts[not_small] + 1L
gap <- gap + 1L
}
}
vec_chop(x, indices)
}vec_check_list — a name the prelude does not declarename: vec_check_list
df_align <- function(
x,
names,
align_direction = c("start", "end")
) {
vec_check_list(x)
if (length(x) == 0) {
return(new_data_frame(rep_named(names, list(character())), size = 0))
}
align_direction <- arg_match(align_direction)
n <- length(x)
p <- length(names)
out <- df_align_transpose(x, p, align_direction = align_direction)
out <- out[!is.na(names)]
names(out) <- names[!is.na(names)]
new_data_frame(out, size = n)
}cli::cli_warn — a name the prelude does not declarename: cli::cli_warn
separate_warn_debug <- function(col, names_sep, vars) {
vars <- debug_name(col, names_sep, vars)
cli::cli_warn("Debug mode activated: adding variables {.var {vars}}.")
}caller_env — a name the prelude does not declarename: caller_env
str_separate_wider_delim <- function(
x,
col,
names,
delim,
names_sep = NULL,
too_few = "error",
too_many = "error",
cols_remove = TRUE,
error_call = caller_env()
) {
if (is_bare_string(delim)) {
delim <- stringr::fixed(delim)
}
if (too_many == "merge") {
if (is.null(names)) {
cli::cli_abort(
'Must provide {.arg names} when {.code too_many = "merge"}.',
call = error_call
)
}
n <- length(names)
} else {
n <- Inf
}
pieces <- stringr::str_split(x, delim, n = n)
lengths <- lengths(pieces)
n_pieces <- ifelse(is.na(x), NA, lengths)
names <- names %||% as.character(seq_len(int_max(lengths, 0)))
p <- length(names)
check_df_alignment(
col,
p,
"pieces",
n_pieces,
too_few = too_few,
too_many = too_many,
advice_short = c(
i = 'Use `too_few = "debug"` to diagnose the problem.',
i = 'Use `too_few = "align_start"/"align_end"` to silence this message.'
),
advice_long = c(
i = 'Use `too_many = "debug"` to diagnose the problem.',
i = 'Use `too_many = "drop"/"merge"` to silence this message.'
),
call = error_call
)
out <- df_align(
x = pieces,
names = names,
align_direction = if (too_few == "align_end") "end" else "start"
)
if (!cols_remove || too_few == "debug" || too_many == "debug") {
out[[col]] <- x
}
if (too_few == "debug" || too_many == "debug") {
separate_warn_debug(col, names_sep, c("ok", "pieces", "remainder"))
sep_loc <- stringr::str_locate_all(x, delim)
sep_last <- map(sep_loc, function(x) if (nrow(x) < p) NA else x[p, "start"])
remainder <- stringr::str_sub(x, sep_last)
remainder[is.na(remainder) & !is.na(x)] <- ""
problem <- !is.na(x) &
((too_few == "debug" & n_pieces < p) |
(too_many == "debug" & n_pieces > p))
out[[debug_name(col, names_sep, "ok")]] <- !problem
out[[debug_name(col, names_sep, "pieces")]] <- n_pieces
out[[debug_name(col, names_sep, "remainder")]] <- remainder
}
out
}check_installed — a name the prelude does not declarename: check_installed
separate_wider_delim <- function(
data,
cols,
delim,
...,
names = NULL,
names_sep = NULL,
names_repair = "check_unique",
too_few = c("error", "debug", "align_start", "align_end"),
too_many = c("error", "debug", "drop", "merge"),
cols_remove = TRUE
) {
check_installed("stringr")
check_data_frame(data)
check_required(cols)
check_dots_empty()
check_string(delim, allow_empty = FALSE)
if (is.null(names) && is.null(names_sep)) {
cli::cli_abort(
"Must specify at least one of {.arg names} or {.arg names_sep}."
)
}
check_character(names, allow_null = TRUE)
if (is_named(names)) {
cli::cli_abort("{.arg names} must be an unnamed character vector.")
}
too_few <- arg_match(too_few)
too_many <- arg_match(too_many)
check_bool(cols_remove)
error_call %<~% current_env()
map_unpack(
data,
{{ cols }},
function(x, col) {
str_separate_wider_delim(
x,
col,
names = names,
delim = delim,
names_sep = names_sep,
too_few = too_few,
too_many = too_many,
cols_remove = cols_remove,
error_call = error_call
)
},
names_sep = names_sep,
names_repair = names_repair
)
}caller_env — a name the prelude does not declarename: caller_env
str_separate_wider_position <- function(
x,
col,
widths,
names_sep = NULL,
too_few = "error",
too_many = "error",
cols_remove = TRUE,
error_call = caller_env()
) {
breaks <- cumsum(c(1L, unname(widths)))[-(length(widths) + 1L)]
expected_width <- sum(widths)
width <- stringr::str_length(x)
check_df_alignment(
col,
expected_width,
"characters",
width,
too_few = too_few,
too_many = too_many,
advice_short = c(
i = 'Use `too_few = "debug"` to diagnose the problem.',
i = 'Use `too_few = "align_start"` to silence this message.'
),
advice_long = c(
i = 'Use `too_many = "debug"` to diagnose the problem.',
i = 'Use `too_many = "drop"` to silence this message.'
),
call = error_call
)
skip <- names(widths) == ""
from <- cbind(start = breaks[!skip], length = widths[!skip])
names <- names(widths)[!skip]
pieces <- stringr::str_sub_all(x, from)
pieces <- map(pieces, function(x) x[x != ""])
out <- df_align(
x = pieces,
names = names,
align_direction = if (too_few == "end") "end" else "start"
)
if (!cols_remove || too_few == "debug" || too_many == "debug") {
out[[col]] <- x
}
if (too_few == "debug" || too_many == "debug") {
separate_warn_debug(col, names_sep, c("ok", "width", "remainder"))
problem <- !is.na(x) &
((too_few == "debug" & width < expected_width) |
(too_many == "debug" & width > expected_width))
out[[debug_name(col, names_sep, "width")]] <- width
out[[debug_name(col, names_sep, "remainder")]] <- stringr::str_sub(
x,
expected_width + 1,
width
)
out[[debug_name(col, names_sep, "ok")]] <- !problem
}
out
}check_installed — a name the prelude does not declarename: check_installed
separate_wider_position <- function(
data,
cols,
widths,
...,
names_sep = NULL,
names_repair = "check_unique",
too_few = c("error", "debug", "align_start"),
too_many = c("error", "debug", "drop"),
cols_remove = TRUE
) {
check_installed("stringr")
check_data_frame(data)
check_required(cols)
check_required(widths)
if (!is_integerish(widths) || !any(have_name(widths))) {
cli::cli_abort("{.arg widths} must be a (partially) named integer vector.")
}
if (any(widths <= 0)) {
cli::cli_abort("All values of {.arg widths} must be positive.")
}
check_dots_empty()
too_few <- arg_match(too_few)
too_many <- arg_match(too_many)
check_bool(cols_remove)
error_call %<~% current_env()
map_unpack(
data,
{{ cols }},
function(x, col) {
str_separate_wider_position(
x,
col,
widths = widths,
names_sep = names_sep,
too_few = too_few,
too_many = too_many,
cols_remove = cols_remove,
error_call = error_call
)
},
names_sep = names_sep,
names_repair = names_repair
)
}caller_env — a name the prelude does not declarename: caller_env
str_separate_wider_regex <- function(
x,
col,
patterns,
names_sep = NULL,
too_few = "error",
cols_remove = TRUE,
error_call = caller_env()
) {
has_name <- names2(patterns) != ""
groups <- stringr::str_c("(", ifelse(has_name, "", "?:"), patterns, ")")
full_match <- stringr::str_c(
"^",
stringr::str_flatten(groups, collapse = ""),
"$"
)
match <- stringr::str_match(x, full_match)
if (ncol(match) != sum(has_name) + 1L) {
cli::cli_abort(
c(
"Invalid number of groups.",
i = 'Did you use "()" instead of "(?:)" inside {.arg patterns}?'
),
call = error_call
)
}
matches <- match[, -1, drop = FALSE]
out <- as_tibble(matches, .name_repair = "none")
colnames(out) <- names2(patterns)[has_name]
if (!cols_remove || too_few == "debug") {
out[[col]] <- x
}
match_count <- ifelse(is.na(x), NA, length(patterns))
remainder <- ifelse(is.na(x), NA, "")
problems <- !is.na(x) & is.na(match[, 1])
no_match <- which(problems)
if (length(no_match) > 0) {
if (too_few == "error") {
cli::cli_abort(
c(
"Expected each value of {.var {col}} to match the pattern, the whole pattern, and nothing but the pattern.",
"!" = "{length(no_match)} value{?s} {?has/have} problem{?s}.",
i = 'Use {.code too_few = "debug"} to diagnose the problem.',
i = 'Use {.code too_few = "align_start"} to silence this message.'
),
call = error_call
)
}
# Progressively relax the matches
for (i in rev(seq_along(groups))) {
partial <- paste0("^", paste(groups[1:i], collapse = ""), "(.*)$")
match <- stringr::str_match(x[no_match], partial)
has_match <- !is.na(match[, 1])
match_idx <- no_match[has_match]
if (length(match_idx) == 0) {
next
}
matches <- as_tibble(
match[has_match, -1, drop = FALSE],
.name_repair = "none"
)
cols <- names2(patterns)[has_name][1:(ncol(matches) - 1)]
out[match_idx, cols] <- matches[1:(ncol(matches) - 1)]
remainder[match_idx] <- matches[[ncol(matches)]]
match_count[match_idx] <- i
no_match <- no_match[!has_match]
if (length(no_match) == 0) {
break
}
}
if (length(no_match) > 0) {
match_count[no_match] <- 0L
remainder[no_match] <- x[no_match]
}
}
if (too_few == "debug") {
separate_warn_debug(col, names_sep, c("ok", "matches", "remainder"))
out[debug_name(col, names_sep, "ok")] <- !problems
out[debug_name(col, names_sep, "matches")] <- match_count
out[debug_name(col, names_sep, "remainder")] <- remainder
}
out
}check_installed — a name the prelude does not declarename: check_installed
separate_wider_regex <- function(
data,
cols,
patterns,
...,
names_sep = NULL,
names_repair = "check_unique",
too_few = c("error", "debug", "align_start"),
cols_remove = TRUE
) {
check_installed("stringr")
check_data_frame(data)
check_required(cols)
check_character(patterns)
if (length(patterns) > 0 && all(!have_name(patterns))) {
cli::cli_abort("{.arg patterns} must be a named character vector.")
}
check_dots_empty()
check_string(names_sep, allow_null = TRUE)
too_few <- arg_match(too_few)
check_bool(cols_remove)
error_call %<~% current_env()
map_unpack(
data,
{{ cols }},
function(x, col) {
str_separate_wider_regex(
x,
col,
patterns = patterns,
names_sep = names_sep,
too_few = too_few,
cols_remove = cols_remove,
error_call = error_call
)
},
names_sep = names_sep,
names_repair = names_repair
)
}UseMethod — a name the prelude does not declarename: UseMethod
full_seq <- function(x, period, tol = 1e-6) {
UseMethod("full_seq")
}check_number_decimal — one of the package’s own names, itself untypedname: check_number_decimal
full_seq.numeric <- function(x, period, tol = 1e-6) {
check_number_decimal(period)
check_number_decimal(tol, min = 0)
rng <- range(x, na.rm = TRUE)
if (
any(
((x - rng[1]) %% period > tol) &
(period - (x - rng[1]) %% period > tol)
)
) {
cli::cli_abort("{.arg x} is not a regular sequence.")
}
# in cases where the last element is within tolerance, pad it so that
# the output length is correct
if (period - ((rng[2] - rng[1]) %% period) <= tol) {
rng[2] <- rng[2] + tol
}
seq(rng[1], rng[2], by = period)
}mostattributes<- — a name the prelude does not declarename: mostattributes<-
restore <- function(old, new) {
mostattributes(new) <- attributes(old)
new
}full_seq — one of the package’s own names, itself untypedname: full_seq
full_seq.Date <- function(x, period, tol = 1e-6) {
restore(x, full_seq(as.numeric(x), period, tol))
}full_seq — one of the package’s own names, itself untypedname: full_seq
full_seq.POSIXct <- function(x, period, tol = 1e-6) {
restore(x, full_seq(as.numeric(x), period, tol))
}"_PACKAGE"local_use_cli — a name the prelude does not declarename: local_use_cli
on_load(local_use_cli())new_environment — a name the prelude does not declarename: new_environment
the <- new_environment()globalVariables — a name the prelude does not declarename: globalVariables
globalVariables(c(".", "name", "value"))tibble::tribble — a name the prelude does not declarename: tibble::tribble
tibble::tribbletibble::tibble — a name the prelude does not declarename: tibble::tibble
tibble::tibbletibble::as_tibble — a name the prelude does not declarename: tibble::as_tibble
tibble::as_tibbletidyselect::all_of — a name the prelude does not declarename: tidyselect::all_of
tidyselect::all_oftidyselect::any_of — a name the prelude does not declarename: tidyselect::any_of
tidyselect::any_oftidyselect::contains — a name the prelude does not declarename: tidyselect::contains
tidyselect::containstidyselect::ends_with — a name the prelude does not declarename: tidyselect::ends_with
tidyselect::ends_withtidyselect::everything — a name the prelude does not declarename: tidyselect::everything
tidyselect::everythingtidyselect::last_col — a name the prelude does not declarename: tidyselect::last_col
tidyselect::last_coltidyselect::matches — a name the prelude does not declarename: tidyselect::matches
tidyselect::matchestidyselect::num_range — a name the prelude does not declarename: tidyselect::num_range
tidyselect::num_rangetidyselect::one_of — a name the prelude does not declarename: tidyselect::one_of
tidyselect::one_oftidyselect::starts_with — a name the prelude does not declarename: tidyselect::starts_with
tidyselect::starts_withcheck_dots_used — a name the prelude does not declarename: check_dots_used
uncount <- function(data, weights, ..., .remove = TRUE, .id = NULL) {
check_dots_used()
UseMethod("uncount")
}check_bool — one of the package’s own names, itself untypedname: check_bool
uncount.data.frame <- function(data, weights, ..., .remove = TRUE, .id = NULL) {
check_bool(.remove)
check_name(.id, allow_null = TRUE)
weights_quo <- enquo(weights)
w <- dplyr::pull(dplyr::mutate(data, `_weight` = !!weights_quo))
out <- vec_rep_each(
data,
w,
error_call = current_env(),
times_arg = "weights"
)
# NOTE it was decided to also remove grouping variables as there is no clear
# best answer. See https://github.com/tidyverse/tidyr/pull/1070
if (.remove && quo_is_symbol(weights_quo)) {
out[[as_string(get_expr(weights_quo))]] <- NULL
}
if (!is.null(.id)) {
out[[.id]] <- sequence(w)
}
reconstruct_tibble(data, out)
}is_false — a name the prelude does not declarename: is_false
collect_indices_info <- function(col, sizes, indices_include, keep_empty) {
out <- list(
indices_include = FALSE,
indices = NULL,
index_ptype = NULL
)
if (is_false(indices_include)) {
return(out)
}
indices <- map(col, vec_names)
unnamed <- vec_detect_missing(indices)
all_unnamed <- all(unnamed)
if (is.null(indices_include) && all_unnamed) {
# Same as `indices_include = FALSE`
return(out)
}
if (all_unnamed) {
# Indices are requested, but none of the elements are named.
# Generate integer column of sequential indices.
indices <- map(sizes, seq_len)
index_ptype <- integer()
} else {
# Indices are requested, and some elements are named.
# For any unnamed elements, generate `NA` indices.
indices[unnamed] <- map(sizes[unnamed], vec_rep, x = "")
index_ptype <- character()
}
if (keep_empty) {
empty <- sizes == 0L
if (any(empty)) {
# `NULL` or typed empty elements get an `NA` index of the right type
index_empty <- vec_init(index_ptype)
indices[empty] <- list(index_empty)
}
}
out$indices_include <- TRUE
out$indices <- indices
out$index_ptype <- index_ptype
out
}new_data_frame — a name the prelude does not declarename: new_data_frame
new_long_frame <- function(x, size, name) {
out <- list(x)
names(out) <- name
new_data_frame(out, n = size)
}new_data_frame — a name the prelude does not declarename: new_data_frame
new_long_indexed_frame <- function(x, index, size, indices_to, values_to) {
out <- list(index, x)
names(out) <- c(indices_to, values_to)
new_data_frame(out, n = size)
}caller_env — a name the prelude does not declarename: caller_env
col_to_long <- function(
col,
name,
values_to,
indices_to,
indices_include,
keep_empty,
error_call = caller_env()
) {
if (vec_is_list(col)) {
ptype <- list_of_ptype(col)
} else {
ptype <- vec_ptype(col)
col <- vec_chop(col)
}
# Avoid expensive dispatch from `[[.list_of`, and allow for `[[<-`.
# We've already captured the `ptype`.
col <- tidyr_new_list(col)
if (!list_all_vectors2(col)) {
cli::cli_abort(
"List-column {.var {name}} must contain only vectors or `NULL`.",
call = error_call
)
}
sizes <- list_sizes(col)
# Collect index info before replacing `NULL`s so `keep_empty` works correctly
info <- collect_indices_info(col, sizes, indices_include, keep_empty)
indices_include <- info$indices_include
indices <- info$indices
index_ptype <- info$index_ptype
size_null <- as.integer(keep_empty)
info <- list_replace_null(col, sizes, ptype = ptype, size = size_null)
col <- info$x
sizes <- info$sizes
if (keep_empty) {
info <- list_replace_empty_typed(col, sizes, ptype = ptype, size = 1L)
col <- info$x
sizes <- info$sizes
}
if (is.null(ptype)) {
# Initialize `ptype` to generate a `ptype` version of the output data frame.
# Important in the size 0 input case.
ptype <- unspecified()
}
if (indices_include) {
ptype <- new_long_indexed_frame(
x = ptype,
index = index_ptype,
size = 0L,
indices_to = indices_to,
values_to = values_to
)
col <- pmap(
list(col, indices, sizes),
function(elt, index, size) {
new_long_indexed_frame(
x = elt,
index = index,
size = size,
indices_to = indices_to,
values_to = values_to
)
}
)
} else {
name <- values_to
ptype <- new_long_frame(ptype, 0L, name)
col <- map2(
col,
sizes,
function(elt, size) new_long_frame(elt, size, name)
)
}
ptype <- vec_ptype_common(ptype, !!!col)
col <- vec_cast_common(!!!col, .to = ptype)
col <- new_list_of(col, ptype = ptype)
col
}glue::glue_data — a name the prelude does not declarename: glue::glue_data
glue_col_names <- function(string, col_names) {
data <- list(col = col_names)
out <- glue::glue_data(data, string, .envir = NULL)
out <- as.character(out)
out
}check_data_frame — one of the package’s own names, itself untypedname: check_data_frame
unnest_longer <- function(
data,
col,
values_to = NULL,
indices_to = NULL,
indices_include = NULL,
keep_empty = FALSE,
names_repair = "check_unique",
simplify = TRUE,
ptype = NULL,
transform = NULL
) {
check_data_frame(data)
check_required(col)
check_name(values_to, allow_null = TRUE)
check_name(indices_to, allow_null = TRUE)
check_bool(indices_include, allow_null = TRUE)
check_bool(keep_empty)
error_call <- current_env()
cols <- tidyselect::eval_select(enquo(col), data, allow_rename = FALSE)
col_names <- names(cols)
n_col_names <- length(col_names)
values_to <- values_to %||% "{col}"
if (is.null(indices_to)) {
indices_to <- vec_paste0(values_to, "_id")
} else {
if (is_false(indices_include)) {
cli::cli_abort(
"Can't use {.code indices_include = FALSE} when {.arg indices_to} is supplied."
)
}
indices_include <- TRUE
}
values_to <- glue_col_names(values_to, col_names)
values_to <- vec_recycle(values_to, size = n_col_names)
indices_to <- glue_col_names(indices_to, col_names)
indices_to <- vec_recycle(indices_to, size = n_col_names)
for (i in seq_along(cols)) {
col <- cols[[i]]
col_name <- col_names[[i]]
col_values_to <- values_to[[i]]
col_indices_to <- indices_to[[i]]
data[[col]] <- col_to_long(
col = data[[col]],
name = col_name,
values_to = col_values_to,
indices_to = col_indices_to,
indices_include = indices_include,
keep_empty = keep_empty
)
}
data <- unchop(data, all_of(col_names), error_call = error_call)
for (i in seq_along(cols)) {
col <- cols[[i]]
data[[col]] <- df_simplify(
x = data[[col]],
ptype = ptype,
transform = transform,
simplify = simplify
)
}
unpack(
data = data,
cols = all_of(col_names),
names_repair = names_repair,
error_call = error_call
)
}caller_env — a name the prelude does not declarename: caller_env
stop_use_names_sep <- function(error_call = caller_env()) {
message <- c(
"Can't unnest elements with missing names.",
i = "Supply {.arg names_sep} to generate automatic names."
)
cli::cli_abort(message, call = error_call)
}caller_env — a name the prelude does not declarename: caller_env
elt_to_wide <- function(x, name, strict, names_sep, error_call = caller_env()) {
if (is.null(x)) {
x <- list()
}
if (!vec_is(x)) {
cli::cli_abort(
"List-column must only contain vectors.",
call = error_call
)
}
if (is.data.frame(x)) {
# Extremely special case for data.frames,
# which we want to treat like lists where we know the type of each element
x <- tidyr_new_list(x)
x <- map(x, list_of)
names <- names2(x)
x <- set_names(x, NULL)
} else {
if (!strict && vec_is_list(x)) {
empty <- list_sizes(x) == 0L
if (any(empty)) {
# Can't use vec_assign(), see https://github.com/r-lib/vctrs/issues/1424
x[empty] <- list(NULL)
}
}
names <- vec_names2(x)
x <- vec_set_names(x, NULL)
x <- vec_chop(x)
}
empty <- names == ""
any_empty <- any(empty)
if (is.null(names_sep)) {
if (any_empty) {
stop_use_names_sep(error_call = error_call)
}
} else {
if (any_empty) {
names[empty] <- as.character(which(empty))
}
names <- apply_names_sep(name, names, names_sep)
}
x <- set_names(x, names)
x <- new_data_frame(x, n = 1L)
x
}caller_env — a name the prelude does not declarename: caller_env
col_to_wide <- function(
col,
name,
strict,
names_sep,
error_call = caller_env()
) {
if (!vec_is_list(col)) {
ptype <- vec_ptype(col)
col <- vec_chop(col)
col <- new_list_of(col, ptype = ptype)
}
# If we don't have a list_of, then a `NULL` `col_ptype` will get converted to
# a 1 row, 0 col tibble for `elt_ptype`
col_ptype <- list_of_ptype(col)
elt_ptype <- elt_to_wide(
col_ptype,
name = name,
strict = strict,
names_sep = names_sep,
error_call = error_call
)
elt_ptype <- vec_ptype(elt_ptype)
# Avoid expensive dispatch from `[[.list_of`
out <- tidyr_new_list(col)
out <- with_indexed_errors(
map(
out,
function(x) {
elt_to_wide(
x = x,
name = name,
strict = strict,
names_sep = names_sep,
error_call = NULL
)
}
),
message = function(cnd) {
c(
i = cli::format_inline("In column: {.code {name}}."),
i = cli::format_inline("In row: {cnd$location}.")
)
},
.error_call = error_call
)
# In the sole case of a list_of<data_frame>, we can be sure that the
# elements of `out` will all be of the same type. Otherwise,
# - If `col` isn't a list-of, we don't know the element type.
# - If `col` is a list-of but not one with a data frame ptype, then we
# don't actually know if all elements have the same ptype, because the
# number of resulting columns per element depends on that element's size.
has_identical_elements <- is_list_of(col) && is.data.frame(col_ptype)
if (has_identical_elements) {
ptype <- elt_ptype
} else {
ptype <- vec_ptype_common(elt_ptype, !!!out)
out <- vec_cast_common(!!!out, .to = ptype)
}
out <- new_list_of(out, ptype = ptype)
out
}check_data_frame — one of the package’s own names, itself untypedname: check_data_frame
unnest_wider <- function(
data,
col,
names_sep = NULL,
simplify = TRUE,
strict = FALSE,
names_repair = "check_unique",
ptype = NULL,
transform = NULL
) {
check_data_frame(data)
check_required(col)
check_string(names_sep, allow_null = TRUE)
check_bool(strict)
error_call <- current_env()
cols <- tidyselect::eval_select(enquo(col), data, allow_rename = FALSE)
col_names <- names(cols)
for (i in seq_along(cols)) {
col <- cols[[i]]
col_name <- col_names[[i]]
data[[col]] <- col_to_wide(
col = data[[col]],
name = col_name,
strict = strict,
names_sep = names_sep
)
}
data <- unchop(data, all_of(col_names), error_call = error_call)
for (i in seq_along(cols)) {
col <- cols[[i]]
data[[col]] <- df_simplify(
x = data[[col]],
ptype = ptype,
transform = transform,
simplify = simplify
)
}
unpack(
data = data,
cols = all_of(col_names),
names_repair = names_repair,
error_call = error_call
)
}map — a name the prelude does not declarename: map
guess_dir <- function(x, col) {
names <- map(x, names)
is_null <- unique(map_lgl(names, is.null))
if (identical(is_null, TRUE)) {
# all unnamed
code <- glue::glue("unnest_longer({col}, indices_include = FALSE)")
reason <- "no element has names"
out <- "longer"
} else if (identical(is_null, FALSE)) {
# all named
common <- reduce(names, intersect)
n_common <- length(common)
if (n_common == 0) {
code <- glue::glue("unnest_longer({col}, indices_include = TRUE)")
reason <- "elements are named, but have no names in common"
out <- "longer_idx"
} else {
code <- glue::glue("unnest_wider({col})")
reason <- glue::glue("elements have {n_common} names in common")
out <- "wider"
}
} else {
code <- glue::glue("unnest_longer({col}, indices_include = FALSE)")
reason <- "mix of named and unnamed elements"
out <- "longer"
}
message(glue::glue("Using `{code}`; {reason}"))
out
}check_required — a name the prelude does not declarename: check_required
unnest_auto <- function(data, col) {
check_required(col)
col <- tidyselect::vars_pull(tbl_vars(data), {{ col }})
x <- data[[col]]
dir <- guess_dir(x, col)
switch(
dir,
longer = unnest_longer(data, {{ col }}, indices_include = FALSE),
longer_idx = unnest_longer(data, {{ col }}, indices_include = TRUE),
wider = unnest_wider(data, {{ col }}, names_repair = "unique")
)
}Failure("Unsupported argument after an ellipsis.")unnest <- function(
data,
cols,
...,
keep_empty = FALSE,
ptype = NULL,
names_sep = NULL,
names_repair = "check_unique",
.drop = deprecated(),
.id = deprecated(),
.sep = deprecated(),
.preserve = deprecated()
) {
deprecated <- FALSE
if (!missing(.preserve)) {
lifecycle::deprecate_warn(
"1.0.0",
"unnest(.preserve = )",
details = "All list-columns are now preserved",
always = TRUE
)
deprecated <- TRUE
.preserve <- tidyselect::vars_select(tbl_vars(data), !!enquo(.preserve))
} else {
.preserve <- NULL
}
if (missing(cols) && missing(...)) {
list_cols <- names(data)[map_lgl(data, is_list)]
cols <- expr(c(!!!syms(setdiff(list_cols, .preserve))))
cli::cli_warn(c(
"`cols` is now required when using `unnest()`.",
i = "Please use `cols = {expr_text(cols)}`."
))
deprecated <- TRUE
}
if (missing(...)) {
cols <- enquo(cols)
} else {
dots <- enquos(cols, ..., .named = TRUE, .ignore_empty = "all")
data <- dplyr::mutate(data, !!!dots)
cols <- expr(c(!!!syms(names(dots))))
unnest_call <- expr(unnest(!!cols))
cli::cli_warn(c(
"`unnest()` has a new interface. See `?unnest` for details.",
i = "Try `df |> {expr_text(unnest_call)}`, with `mutate()` if needed."
))
deprecated <- TRUE
}
if (!is_missing(.drop)) {
lifecycle::deprecate_warn(
"1.0.0",
"unnest(.drop = )",
details = "All list-columns are now preserved.",
always = TRUE
)
deprecated <- TRUE
}
if (!is_missing(.id)) {
lifecycle::deprecate_warn(
"1.0.0",
"unnest(.id = )",
details = "Manually create column of names instead.",
always = TRUE
)
deprecated <- TRUE
first_col <- tidyselect::vars_select(tbl_vars(data), !!cols)[[1]]
data[[.id]] <- names(data[[first_col]])
}
if (!is_missing(.sep)) {
lifecycle::deprecate_warn(
"1.0.0",
"unnest(.sep = )",
details = glue("Use `names_sep = '{.sep}'` instead.")
)
deprecated <- TRUE
names_sep <- .sep
}
if (deprecated) {
return(unnest(
data,
cols = !!cols,
names_sep = names_sep,
keep_empty = keep_empty,
ptype = ptype,
names_repair = tidyr_legacy
))
}
UseMethod("unnest")
}current_env — a name the prelude does not declarename: current_env
unnest.data.frame <- function(
data,
cols,
...,
keep_empty = FALSE,
ptype = NULL,
names_sep = NULL,
names_repair = "check_unique",
.drop = "DEPRECATED",
.id = "DEPRECATED",
.sep = "DEPRECATED",
.preserve = "DEPRECATED"
) {
error_call <- current_env()
cols <- tidyselect::eval_select(
expr = enquo(cols),
data = data,
allow_rename = FALSE
)
cols <- unname(cols)
data <- unchop(
data = data,
cols = all_of(cols),
keep_empty = keep_empty,
ptype = ptype,
error_call = error_call
)
unpack(
data = data,
cols = all_of(cols),
names_sep = names_sep,
names_repair = names_repair,
error_call = error_call
)
}as_tibble — a name the prelude does not declarename: as_tibble
unnest.rowwise_df <- function(
data,
cols,
...,
keep_empty = FALSE,
ptype = NULL,
names_sep = NULL,
names_repair = "check_unique"
) {
out <- unnest.data.frame(
as_tibble(data),
{{ cols }},
keep_empty = keep_empty,
ptype = ptype,
names_sep = names_sep,
names_repair = names_repair
)
out <- dplyr::grouped_df(out, dplyr::group_vars(data))
out
}run_on_load — a name the prelude does not declarename: run_on_load
.onLoad <- function(libname, pkgname) {
run_on_load()
}