Learn R Programming

lambda.tools (version 1.0.9)

anylength: Get the generic length of an object

Description

This function gets the generic length of an object.

Arguments

data
Any indexable data structure

Value

The conceptual 'length' of a data structure.

Usage

anylength(data)

Details

This function consolidates size dimensions for one and two dimensional data structures. The idea is that many operations require knowing either how long a vector is or how many rows are in a matrix. So rather than switching between length and nrow, anylength provides the appropriate polymorphism to return the proper value. When working with libraries, it is easy to forget the return type of a function, particularly when there are a lot of switches between vectors, matrices, and other data structures. This function along with its anynames counterpart provides a single interface for accessing this information across objects The core assumption is that in most cases length is semantically synonymous with nrow such that the number of columns in two-dimensional structures is less consequential than the number of rows. This is particularly true of time-based objects, such as zoo or xts where the number of observations is equal to the number of rows in the structure. When working with functions that are polymorphic, lambda.r function clauses with guard conditions on the length of the input data structure can use anylength instead of using length or nrow, which preserves polymorphism and reduces the number of function clauses necessary. For example, instead of one clause to check length and another to check nrow, anylength can test for both situations in a single clause.
slice(x, expression) %::% a : logical : list slice(x, expression) %when% { length(expression) == length(x) } slice(x, expression) %::% a : logical : slice(x, expression) %when% { length(expression) == nrow(x) }
These two clauses can be replaced with
slice(x, expression) %::% a : logical : . slice(x, expression) %when% { length(expression) == anylength(x) }
Another use of anylength is when working with sapply. The output value is governed by the result of the higher-order function, so it is difficult to know a priori whether the result will be a vector or a matrix. With anylength it doesn't matter since the same function is used in either case.

Examples

Run this code
# Get the rows of the matrix
anylength(matrix(c(1,2,3,4,5,6), ncol=2))

# Get the length of the vector
anylength(c(1,2,3,4,5))

Run the code above in your browser using DataLab