Skip to main content
v2026.11,986 entries · CC-BY 4.0

Array in R: array(), Indexing, dimnames and aperm

Create and index arrays in R: fill order, dimnames, slicing, drop=FALSE, index matrices and aperm(), with worked examples.

Written and maintained by CASRAI Editorial Board

Published

On this page

An array in R is a vector with a dim attribute: a block of values of one type arranged along one, two or more dimensions, created with array(data, dim, dimnames). A two-dimensional array is a matrix, and anything with three or more dimensions behaves like a stack of matrices. Values are filled with the leftmost subscript moving fastest, so the order in which you supply data decides which cell each value lands in, and getting that order right is the main thing to learn about arrays.

This guide works through array() with small, checkable examples: how filling and recycling work, how to name dimensions with dimnames, how to extract slices (including with an index matrix), when drop = FALSE matters, how aperm() differs from t(), and how to summarise over one dimension. It is written for researchers who meet arrays when handling replicates, conditions, time points or repeated measures, and it is based on the R reference manuals listed under Sources. It sits alongside the CASRAI guides on vectors in R, lists in R and dim() in R.

What array in R is used for in research

The R reference page for array describes an array as a vector with a "dim" attribute and optional "dimnames". That makes it the natural container whenever a measurement is indexed by more than two factors at once. Typical research shapes are subject by time point by condition, sample by gene by replicate, or site by year by species. Because every cell holds the same type of value, an array suits a single measured quantity, such as a score or a count, laid out along several design factors.

Three relationships are worth knowing before you start. First, a 2-D array is a matrix. Second, a 1-D array looks like a vector but the manual notes that some functions treat the two differently, which matters when you convert with as.array(). Third, a data frame is not an array: when your columns have different types or you need one row per observation, a data frame is the better container and an array is a convenient reshaping target for a single numeric measure.

How to install or access array in R

There is nothing to install for arrays. array(), aperm(), dim() and the indexing operators belong to R’s base package, so they are available in every R session. R itself is distributed from the Comprehensive R Archive Network at cran.r-project.org, and the manuals used here are the official ones: the “An Introduction to R” manual on CRAN and the R reference pages mirrored at stat.ethz.ch. Inside R, ?array, ?aperm and ?Extract open the same help pages.

How to create, index and reshape an array in R step by step

The examples below use one small, illustrative data set: two subjects, three time points and two conditions, with values 1 to 12 standing in for a measured score. It is invented for demonstration and does not come from any study. The printed output was derived from the fill rules in the R manual and checked cell by cell.

Step 1. Create an array and learn the fill order

  1. Call array() with a data vector and a dim vector. Each dim value is a non-negative integer, and the manual states that their product must match the length of the array.
    x = array(1:24, dim = c(2, 3, 4))
    dim(x)
    # [1] 2 3 4
  2. Remember that the values are taken “with the leftmost subscript moving fastest”. In x, the first index changes first, then the second, then the third, so x[2, 3, 4] is the 24th value and x[1, 2, 3] is the 15th (the position is (i−1) + (j−1)×2 + (k−1)×6 + 1).
    x[2, 3, 4]
    # [1] 24
    x[1, 2, 3]
    # [1] 15
  3. If data is shorter than the array, it is recycled. The manual’s own example recycles 1:3 “2 2/3 times”:
    array(1:3, c(2, 4))
    #      [,1] [,2] [,3] [,4]
    # [1,]    1    3    2    1
    # [2,]    2    1    3    2

    If data has length zero, NA of the appropriate type is used (0 for raw vectors).

Step 2. Name the dimensions with dimnames

  1. Pass dimnames as a list with one component per dimension, each either NULL or a character vector as long as that dimension. The manual says a dimnames argument that is not a list is ignored, so a bare character vector silently does nothing.
    scores = array(1:12, dim = c(2, 3, 2),
      dimnames = list(c("S1", "S2"),
                      c("t1", "t2", "t3"),
                      c("control", "treated")))
    scores
    # , , control
    #
    #    t1 t2 t3
    # S1  1  3  5
    # S2  2  4  6
    #
    # , , treated
    #
    #    t1 t2 t3
    # S1  7  9 11
    # S2  8 10 12
  2. Optionally name the dimensions themselves, for example names(dimnames(scores)) = c("subject", "time", "condition"). Printing then labels each slice with the dimension name as well as the level.

Step 3. Extract single cells and slices

  1. Give one index per dimension, separated by commas. An empty index selects the whole range of that dimension, as the “An Introduction to R” manual shows with a[2,,], a sub-array that fixes the first index.
    scores["S2", "t3", "treated"]
    # [1] 12
    scores[, , "treated"]
    #    t1 t2 t3
    # S1  7  9 11
    # S2  8 10 12
    scores[1, , ]
    #    control treated
    # t1       1       7
    # t2       3       9
    # t3       5      11
  2. Use negative integers to leave slices out, for example scores[-1, , ] drops the first subject. The manual states that character indices never partially match, and that an empty string or NA index matches no name.

Step 4. Keep or drop extent-one dimensions

  1. By default, extraction with drop = TRUE coerces the result “to the lowest possible dimension”. A 2 × 3 × 1 slice therefore comes back as a 2 × 3 matrix.
    dim(scores[, , "treated"])
    # [1] 2 3
    dim(scores[, , "treated", drop = FALSE])
    # [1] 2 3 1
  2. Use drop = FALSE inside functions that expect a fixed number of dimensions. The manual notes that drop only works for extracting elements, not for replacement.

Step 5. Select or replace cells with an index matrix

  1. Build a numeric matrix with one column per dimension and one row per cell you want. This is the “third form of indexing” in the manual. The manual’s example uses a 4 × 5 array and a three-row index matrix:
    x2 = array(1:20, dim = c(4, 5))
    i = array(c(1:3, 3:1), dim = c(3, 2))
    x2[i]
    # [1]  9  6  3
    x2[i] = 0

    The three rows of i pick cells (1,3), (2,2) and (3,1), which hold 9, 6 and 3, and the assignment sets exactly those cells to zero.

  2. Check the index matrix before using it: negative values are not allowed, rows of zeros are ignored, and a row containing NA gives NA. A character matrix works only if the array has dimnames.

Step 6. Permute dimensions with aperm()

  1. Call aperm(a, perm), where perm lists the old dimensions in their new order. If perm is omitted, the dimensions are reversed.
    y = array(1:24, 2:4)
    dim(aperm(y, c(2, 1, 3)))
    # [1] 3 2 4
    dim(aperm(y))
    # [1] 4 3 2
  2. For a matrix, aperm(A, c(2, 1)) is the same as t(A), and the R documentation recommends t() for that case. The documented check for higher dimensions is t(aperm(y, c(2, 1, 3))[, , 2]) equal to y[, , 2]. With resize = FALSE, aperm() keeps the original dimensions and drops the dimnames, so leave the default in place unless you want that.
  3. With named dimnames, perm can be given as character names rather than positions, which is easier to read in analysis scripts.

Step 7. Summarise over a dimension

  1. Use apply() to collapse one or more dimensions of an array; see the CASRAI guide to the apply family in R for the full argument set. Summing over subjects and time leaves one value per condition:
    apply(scores, 3, sum)
    # control treated
    #      21      57
  2. Keeping two dimensions gives a matrix of subject-by-condition means:
    apply(scores, c(1, 3), mean)
    #    control treated
    # S1       3       9
    # S2       4      10
  3. To build arrays from two vectors, outer() (or %o%) returns an array whose dimensions are the concatenation of the dimensions of its two arguments, so outer(1:2, array(1:6, c(2, 3))) has dimensions 2 × 2 × 3.

How to read the output

When R prints an array with three or more dimensions it prints one matrix per combination of the higher indices, introduced by a header such as , , control. The row and column labels come from the first two dimnames components, and without dimnames R prints positions such as [1,] and [,2]. If you named the dimensions, the header also shows the dimension name. Read a cell as row, column, slice.

To confirm what you have, three functions are enough. dim() returns the extents. is.array() returns TRUE when the object has a dim attribute of positive length, which is the manual’s definition, so is.array(1:3) is FALSE while is.array(matrix(1:4, 2)) is TRUE. dim(as.array(letters)) returns 26: the manual’s own example shows that as.array() turns a plain vector into a 1-D array and attaches dimnames if the vector had names.

Troubleshooting array in R

  • The values are in the wrong cells. Filling runs down the first dimension first. If your data is stored row by row, build the array with the dimensions in the order your data varies, then reorder with aperm().
  • The array silently has no names. dimnames must be a list with one component per dimension; the manual states that anything else is ignored.
  • A slice lost a dimension. This is drop = TRUE at work. Use drop = FALSE to keep extent-one dimensions.
  • A subscript out of bounds error. The index is larger than that dimension’s extent. The reference manual says these are signalled as errors of class subscriptOutOfBoundsError. Check dim() first.
  • A character index finds nothing. Character indexing needs dimnames, never partially matches, and an empty string or NA matches no name.
  • The index matrix fails. It needs one column per dimension, no negative values, and the matrix form of indexing only extracts or replaces cells, so use ordinary negative subscripts to exclude slices.
  • A 1-D array behaves differently from a vector. The manual notes that some functions treat them differently. Convert with as.vector() if you need a plain vector.

Free alternatives to array in R

R is the reference implementation of this array model, and the base package is all you need. If your pipeline lives elsewhere, the closest equivalents are the following; the main differences are the memory order and the index origin, which cause the most mistakes when moving an array between tools.

Tool Array object What the documentation says
Base R array() Fills with the leftmost subscript moving fastest; optional dimnames per dimension
NumPy (Python) ndarray A multidimensional container of items of the same type and size; new arrays are in row-major (C) order unless specified

The NumPy documentation’s example, x[1, 2] for the “second row, third column”, shows its first index is 0, whereas R counts from 1. When exchanging arrays between R and NumPy, the fill-order difference described above is the first thing to test with a small asymmetric array.

Sources

Data: Ways to index an R array and what each returns

Compiled from the R reference manual pages for array and Extract and the An Introduction to R manual: each indexing form for a multidimensional R array, its syntax, and the documented rule that governs the result. Syntax examples use the three-dimensional scores array from the guide.

Ways to index an R array and what each returns
Indexing formExample syntaxDocumented behaviourSource page
One index per dimensionscores["S2", "t3", "treated"]Selects one cell; an empty index selects the whole range of that dimension (a[2,,] fixes the first index)An Introduction to R, arrays
Negative integersscores[-1, , ]Leaves the named elements or slices out of the selectionR reference: Extract
Numeric index matrixx[i] where i has one column per dimensionExtracts or replaces the addressed cells; negative values not allowed, zero rows ignored, NA rows give NAAn Introduction to R, arrays; R reference: Extract
Character index matrixx[m] where m is a character matrixWorks only if the array has dimnames; empty or NA indices match no nameR reference: Extract
drop argumentscores[, , "treated", drop = FALSE]With drop = TRUE the result is coerced to the lowest possible dimension; applies to extraction only, not replacementR reference: Extract

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · free to try

Ask about Array in R: array(), Indexing, dimnames and aperm

2 free questions a day, no account.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →