vec_slice {vctrs} | R Documentation |
This provides a common interface to extracting and modifying observations
for all vector types, regardless of dimensionality. It is an analog to [
that matches vec_size()
instead of length()
.
vec_slice(x, i) vec_slice(x, i) <- value vec_assign(x, i, value)
x |
A vector |
i |
An integer, character or logical vector specifying the positions or
names of the observations to get/set.
Specify |
value |
Replacement values. |
A vector of the same type as x
.
Support for S3 objects depends on whether the object implements a
vec_proxy()
method.
When a vec_proxy()
method exists, the proxy is sliced and
vec_restore()
is called on the result.
Otherwise vec_slice()
falls back to the base generic [
.
Note that S3 lists are treated as scalars by default, and will
cause an error if they don't implement a vec_proxy()
method.
vec_slice()
only slices along one dimension. For
two-dimensional types, the first dimension is subsetted.
vec_slice()
preserves attributes by default.
vec_slice<-()
is type-stable and always returns the same type
as the LHS.
x <- sample(10) x vec_slice(x, 1:3) # You can assign with the infix variant: vec_slice(x, 2) <- 100 x # Or with the regular variant that doesn't modify the original input: y <- vec_assign(x, 3, 500) y x # Slicing objects of higher dimension: vec_slice(mtcars, 1:3) # Type stability -------------------------------------------------- # The assign variant is type stable. It always returns the same # type as the input. x <- 1:5 vec_slice(x, 2) <- 20.0 # `x` is still an integer vector because the RHS was cast to the # type of the LHS: vec_ptype(x) # Compare to `[<-`: x[2] <- 20.0 vec_ptype(x) # Note that the types must be coercible for the cast to happen. # For instance, you can cast a character vector to an integer: vec_cast("1", integer()) # But these types are not coercible: try(vec_ptype2("1", integer())) # Hence you cannot assign character values to an integer or double # vector: try(vec_slice(x, 2) <- "20")