index0 {index0}R Documentation

Zero-based indexing of vectors

Description

Normally R is indexed from 1, but with the special index0 class, you can have vectors that are indexed from zero. Works both for subsetting (extraction) and (sub-)assignment. An index0 object is just like a normal vector or matrix, but x[i] returns or replaces the (i+1)th index.

Usage

## S3 method for class 'index0'
x[i, j, ...]

## S3 replacement method for class 'index0'
x[i, j, ...] <- value

as.index0(x)

as.index1(x)

is.index0(x)

index_from_0(x)

## S3 method for class 'index0'
print(x, ...)

Arguments

x

object from which to extract element(s) or in which to replace element(s)

i, j

indices specifying elements to extract or replace. Starting from 1.

...

other arguments passed to generic methods.

value

typically an array-like R object of a similar class as x.

Details

Assign the class index0 to a vector, using as.index0() or index_from_0(), then use the subset operators normally and they will be indexed from zero. You can reverse the operation (reset to indexing from 1) with as.index1() or by manually removing the index0 class. Character indices seem to be unaffected. Be cautious with logical indices. See examples.

Value

as.index0 returns the input (typically a vector or matrix) unchanged except for the addition of an index0 class attribute, which enables the zero-based indexing behaviour. Use as.index1 to remove this class again, if present.

If x is a zero-indexed object with class index0, then x[i] returns an appropriate subset of x. The returned subset is also zero-indexed. x[i] <- value changes the ith element (effectively (i+1)th element in ordinary R code) in place.

is.index0(x) returns TRUE if x is indexed from zero, otherwise FALSE.

Source

Partially inspired by this Stack Overflow answer: Zero based arrays/vectors in R

Examples

# Vectors
v <- as.index0(letters)
v[0:3]
v[c(0, 2)] <- c('zeroth', 'second')
v

# Matrices and arrays
m <- index_from_0(matrix(1:4, 2))
m[0, 1]
m[0, 1] <- 99
m


[Package index0 version 0.0.1 Index]