vctrs
vctrs copied to clipboard
`vec_cast()` should preserve names
vec_cast(c(a = 1, b = 3), int())
#> [1] 1 3
Two notes:
First, when dimensions (that aren't the 1st dim) are broadcast, should we recycle existing names or drop them? Current behavior is recycling, which we get through [
automatically (we should definitely test these expectations if we don't):
vctrs::vec_cast(
matrix(1, dimnames = list("r1", "c1")),
matrix(1, ncol = 2)
)
#> c1 c1
#> r1 1 1
Second, it seems that shape_broadcast()
drops dim names when the dimensionality changes due to the dim(x) <-
step here https://github.com/r-lib/vctrs/blob/ba92613dc230beea237aa0636b31f534b6900c5c/R/shape.R#L62
vctrs::vec_cast(
c(x = 1),
matrix(1, dimnames = list("r1", "c1"))
)
#> [,1]
#> [1,] 1
I think it makes sense to recycle names while broadcasting. The names of the first dimension should always match the source vector.
If x
is unnamed and to
is named, should x
gain a vector of empty names? This doesn't seem consistent with the idea of preserving the names of x
.
This is related to the question of whether namedness is part of prototypes, and whether vec_ptype()
should strip the names.
If x is unnamed and to is named, should x gain a vector of empty names?
I would say no, I don't think the vec-names of to
are considered at all
If we preserve names, shouldn't we preserve dimensions?
oh no because broadcasting is part of the common type determination.
This is an issue with vec_c()
and vec_unchop()
when named inputs are cast
library(vctrs)
vec_c(c(x = 1), 1)
#> x
#> 1 1
# casting dropped names
vec_c(c(x = 1L), 1)
#> [1] 1 1
args <- list(c(x = 1), 1)
vec_unchop(args, indices = list(1, 2))
#> x
#> 1 1
# casting dropped names
args <- list(c(x = 1L), 1)
vec_unchop(args, indices = list(1, 2))
#> [1] 1 1
Found while investigating https://github.com/r-lib/vctrs/issues/1263