vec_size(x) returns the size of a vector. This is distinct from the length() of a vector because it generalises to the "number of observations" for 2d structures, i.e. it's the number of rows in matrix or a data frame. This definition has the important property that every column of a data frame (even data frame and matrix columns) have the same size. vec_size_common(...) returns the common size of multiple vectors.

vec_size(x)

vec_size_common(..., .size = NULL)

Arguments

x, ...

Vector inputs

.size

If NULL, the default, the output size is determined by recycling the lengths of all elements of .... Alternatively, you can supply .size to force a known size.

Value

An integer (or double for long vectors). Will throw an error if x is not a vector.

vec_size_common() will return NULL if all inputs are NULL or absent.

Details

There is no vctrs helper that retrieves the number of columns: as this is a property of the type.

vec_size() is equivalent to NROW() but has a name that is easier to pronounce, and throws an error when passed non-vector inputs.

Invariants

  • vec_size(dataframe) == vec_size(dataframe[[i]])

  • vec_size(matrix) == vec_size(matrix[, i, drop = FALSE])

  • vec_size(vec_c(x, y)) == vec_size(x) + vec_size(y)

See also

vec_slice() for a variation of [ compatible with vec_size(), and vec_recycle() to recycle vectors to common length.

Examples

vec_size(1:100)
#> [1] 100
vec_size(mtcars)
#> [1] 32
vec_size(array(dim = c(3, 5, 10)))
#> [1] 3
vec_size(NULL)
#> [1] 0
# Because vec_size(vec_c(NULL, x)) == # vec_size(NULL) + vec_size(x) == # vec_size(x) vec_size_common(1:10, 1:10)
#> [1] 10
vec_size_common(1:10, 1)
#> [1] 10
vec_size_common(1:10, integer())
#> [1] 0