vec_as_index {vctrs}R Documentation

Create an index

Description

This provides a means of standardizing common indexing methods such as integer, character or logical indexing. The input is a vector of one of these three types, and the output is always an integer vector that can be used for subsetting.

Usage

vec_as_index(i, n, names = NULL)

Arguments

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]).

n

A single integer representing the total size of the object that i is meant to index into.

names

If i is a character vector, names should be a character vector that i will be matched against to construct the index. Otherwise, not used. The default value of NULL will result in an error if i is a character vector.

Value

An integer vector that can be used as an index in a subsetting operation.

Examples

x <- array(1:6, c(2, 3))
dimnames(x) <- list(c("r1", "r2"), c("c1", "c2", "c3"))

# The most common use case validates row indices
vec_as_index(1, vec_size(x))

# Negative indices can be used to index from the back
vec_as_index(-1, vec_size(x))

# Character vectors can be used if `names` are provided
vec_as_index("r2", vec_size(x), rownames(x))

# You can also construct an index for dimensions other than the first
vec_as_index(c("c2", "c1"), ncol(x), colnames(x))


[Package vctrs version 0.2.1 Index]