vctrs icon indicating copy to clipboard operation
vctrs copied to clipboard

Add `vec_slice2()` and `vec_assign2()`

Open lionel- opened this issue 3 years ago • 2 comments

Branched from #1226.

Following vec_chop2() and vec_map(), this further explores the idea of "extracting" variants of vctrs primitives.

  • With atomic vectors, vec_slice2() and vec_assign2() are equivalent to vec_slice() and vec_assign(). The only difference is that vec_slice2() zaps the names of the result.

  • vec_slice2() with lists makes use of the list storage requirement and calls .subset2().

  • vec_assign2() with lists wraps the RHS into a list. Genericity is ensured by vec_assign() which coerces the RHS (now a list) to the type of the LHS (a list type). This allows the class of the LHS to initialise attributes, possibly based on the contents of the RHS.

One big difference with [[<- is that NULL values are not treated as a deletion sentinel.

x <- list(foo = 1, bar = 2)

vec_assign2(x, 2, NULL)
#> $foo
#> [1] 1
#>
#> $bar
#> NULL

There is currently no way to remove elements:

vec_assign2(x, 2, zap())
#> Error: Can't zap elements.

These operations are unexported for now.

lionel- avatar Aug 19 '20 15:08 lionel-

Closes https://github.com/r-lib/vctrs/issues/141 Closes https://github.com/r-lib/vctrs/pull/626

DavisVaughan avatar Sep 02 '20 18:09 DavisVaughan

Should [[<-.vctrs_vctr use vec_assign2()? I guess it would change the behavior of assigning NULL into list-based vctrs

DavisVaughan avatar Sep 02 '20 20:09 DavisVaughan