add_dimnames: Add dimension names (to arrays).

View source: R/array_fun.R

add_dimnamesR Documentation

Add dimension names (to arrays).

Description

add_dimnames adds (or re-assigns) dimension names to arrays.

Usage

add_dimnames(
  x,
  dnames = c("row", "col", "tab"),
  prefix = c("r", "c", "t"),
  sep = ""
)

Arguments

x

An array to which dimension names are to be added.

dnames

A character vector of dimension names. If length(dnames == 1), a numeric digit is added to signal the dimension number. If length(dnames) exceeds the number of dimensions, it is truncated. If the number of dimensions exceeds length(dnames), dnames are created from LETTERS. Default: dnames = c("row", "col", "tab").

prefix

A character vector of prefixes (whose length must match the number of dimensions of x). Default: prefix = c("r", "c", "t") (for row, column, and table).

sep

A separator (as character) between prefix and numeric indices. Default: sep = "".

Details

Although add_dimnames is intended for arrays, it also works for atomic vectors (yielding a named vector) and data frames (yielding new row and column names) but not other lists.

As R objects of class matrix, table, and xtabs are also arrays add_dimnames works for them as well.

See provideDimnames (from base R) for a related function.

Value

Input x with dimension names.

See Also

provideDimnames is a more basic version.

Other array functions: ctable(), expand_freq_table(), flatten_array(), subtable()

Examples

a <- array(1:24, dim = c(3, 4, 2))
add_dimnames(a)
add_dimnames(a, dnames = "dim", sep = "_")
add_dimnames(a, dnames = c("X", "Y", "Layer", "XYZ"), prefix = c("x", "y", "l"), sep = "_")

# More dimensions:
b <- array(1:2^5, dim = rep(2, 5))
add_dimnames(b)
add_dimnames(b, dnames = "D")
add_dimnames(b, dnames = "dim", prefix = c("r", "c", "l", "m", "n"), sep = "_")

# For a table:
add_dimnames(UCBAdmissions)

# For data frames:
c <- data.frame(let = letters[1:4], num = 5:8)
add_dimnames(c, prefix = c("r", "c"))
add_dimnames(c)

# For atomic vectors:
d <- 1:4
add_dimnames(d, prefix = "nr")  # adding named elements
add_dimnames(d, prefix = letters[1:4], sep = "_")

# For scalars:
add_dimnames(NA)

# For lists (that are NOT data frames):
l <- list(1:2, letters[1:3])
add_dimnames(l)  # return NA


hneth/i2ds documentation built on Aug. 17, 2024, 9:31 p.m.