vctrs icon indicating copy to clipboard operation
vctrs copied to clipboard

`vec_cast()` should preserve names

Open lionel- opened this issue 4 years ago • 7 comments

vec_cast(c(a = 1, b = 3), int())
#> [1] 1 3

lionel- avatar Oct 17 '19 18:10 lionel-

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

DavisVaughan avatar Oct 17 '19 18:10 DavisVaughan

I think it makes sense to recycle names while broadcasting. The names of the first dimension should always match the source vector.

lionel- avatar Oct 17 '19 18:10 lionel-

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.

lionel- avatar Apr 20 '20 13:04 lionel-

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

DavisVaughan avatar Apr 20 '20 14:04 DavisVaughan

If we preserve names, shouldn't we preserve dimensions?

lionel- avatar May 05 '20 07:05 lionel-

oh no because broadcasting is part of the common type determination.

lionel- avatar May 05 '20 07:05 lionel-

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

DavisVaughan avatar Sep 22 '20 19:09 DavisVaughan