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

Arguments

x

A vector

i

An integer, character or logical vector specifying the positions or names of the observations to get/set. Specify TRUE to index all elements (as in x[]), or NULL, FALSE or integer() to index none (as in x[NULL]).

value

Replacement values.

Details

  • vec_slice() is an S3 generic for which you can implement methods. The default method calls [.

  • vec_restore() is called on the slice vector to restore the class and attributes.

Differences with base R subsetting

  • vec_slice() only slices along one dimension. For two-dimensional types, the first dimension is subsetted.

  • vec_slice() preserves attributes by default.

Examples

x <- sample(10) x
#> [1] 9 10 5 8 7 2 1 3 4 6
vec_slice(x, 1:3)
#> [1] 9 10 5
vec_slice(x, 2L) <- 100 x
#> [1] 9 100 5 8 7 2 1 3 4 6
vec_slice(mtcars, 1:3)
#> mpg cyl disp hp drat wt qsec vs am gear carb #> 1 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 #> 2 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 #> 3 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1