| 1 |
|
| 2 |
# The `sel_` prefixed operations match on both values and names, with |
| 3 |
# unnamed elements matching named ones |
| 4 |
sel_union <- function(x, y) { |
| 5 |
if (any_valid_names(names(x)) || any_valid_names(names(y))) { |
| 6 |
sel_operation(x, y, vctrs::vec_set_union) |
| 7 |
} else { |
| 8 |
vctrs::vec_set_union(x, y) |
| 9 |
} |
| 10 |
} |
| 11 |
sel_intersect <- function(x, y) { |
| 12 |
if (any_valid_names(names(x)) || any_valid_names(names(y))) { |
| 13 |
sel_operation(x, y, vctrs::vec_set_intersect) |
| 14 |
} else { |
| 15 |
vctrs::vec_set_intersect(x, y) |
| 16 |
} |
| 17 |
} |
| 18 |
sel_unique <- function(x) { |
| 19 |
if (any_valid_names(names(x))) { |
| 20 |
x <- vctrs::new_data_frame(list(value = x, names = names2(x))) |
| 21 |
x <- propagate_names(x) |
| 22 |
out <- vctrs::vec_unique(x) |
| 23 |
set_names(out$value, out$names) |
| 24 |
} else { |
| 25 |
vctrs::vec_unique(x) |
| 26 |
} |
| 27 |
} |
| 28 |
|
| 29 |
# Set difference and set complement must validate their RHS eagerly, |
| 30 |
# otherwise OOB elements might be selected out and go unnoticed |
| 31 |
sel_diff <- function(x, y, vars = NULL, error_call = caller_env()) { |
| 32 |
if (!is_null(vars)) { |
| 33 |
y <- loc_validate(y, vars, call = error_call) |
| 34 |
} |
| 35 |
if (any_valid_names(names(x)) && any_valid_names(names(y))) { |
| 36 |
sel_operation(x, y, vctrs::vec_set_difference) |
| 37 |
} else { |
| 38 |
vctrs::vec_set_difference(x, y) |
| 39 |
} |
| 40 |
} |
| 41 |
sel_complement <- function(x, vars = NULL, error_call = caller_env()) { |
| 42 |
sel_diff(seq_along(vars), x, vars, error_call = error_call) |
| 43 |
} |
| 44 |
|
| 45 |
sel_operation <- function(x, y, sel_op) { |
| 46 |
x <- vctrs::new_data_frame(list(value = x, names = names2(x))) |
| 47 |
y <- vctrs::new_data_frame(list(value = y, names = names2(y))) |
| 48 |
|
| 49 |
x <- propagate_names(x, y) |
| 50 |
y <- propagate_names(y, x) |
| 51 |
|
| 52 |
out <- sel_op(x, y) |
| 53 |
set_names(out$value, out$names) |
| 54 |
} |
| 55 |
propagate_names <- function(x, from = NULL) { |
| 56 |
unnamed <- x$names == "" |
| 57 |
if (!any(unnamed)) { |
| 58 |
return(x) |
| 59 |
} |
| 60 |
|
| 61 |
# Match names inside `x` first, so we preserve order |
| 62 |
from <- vctrs::vec_c(x, from) |
| 63 |
|
| 64 |
# Prevent unnamed elements from matching |
| 65 |
vctrs::vec_slice(from$value, from$names == "") <- NA |
| 66 |
|
| 67 |
matches <- match( |
| 68 |
x$value[unnamed], |
| 69 |
from$value, |
| 70 |
nomatch = 0L |
| 71 |
) |
| 72 |
x$names[unnamed][matches != 0L] <- from$names[matches] |
| 73 |
|
| 74 |
x |
| 75 |
} |