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
- Call
array()with a data vector and adimvector. Eachdimvalue 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 - 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, sox[2, 3, 4]is the 24th value andx[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 - If
datais shorter than the array, it is recycled. The manual’s own example recycles1:3“2 2/3 times”:array(1:3, c(2, 4)) # [,1] [,2] [,3] [,4] # [1,] 1 3 2 1 # [2,] 2 1 3 2If
datahas length zero,NAof the appropriate type is used (0 for raw vectors).
Step 2. Name the dimensions with dimnames
- Pass
dimnamesas a list with one component per dimension, each eitherNULLor a character vector as long as that dimension. The manual says adimnamesargument 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 - 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
- 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 - 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 orNAindex matches no name.
Step 4. Keep or drop extent-one dimensions
- By default, extraction with
drop = TRUEcoerces 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 - Use
drop = FALSEinside functions that expect a fixed number of dimensions. The manual notes thatdroponly works for extracting elements, not for replacement.
Step 5. Select or replace cells with an index matrix
- 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] = 0The three rows of
ipick cells (1,3), (2,2) and (3,1), which hold 9, 6 and 3, and the assignment sets exactly those cells to zero. - Check the index matrix before using it: negative values are not allowed, rows of zeros are ignored, and a row containing
NAgivesNA. A character matrix works only if the array has dimnames.
Step 6. Permute dimensions with aperm()
- Call
aperm(a, perm), wherepermlists the old dimensions in their new order. Ifpermis 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 - For a matrix,
aperm(A, c(2, 1))is the same ast(A), and the R documentation recommendst()for that case. The documented check for higher dimensions ist(aperm(y, c(2, 1, 3))[, , 2])equal toy[, , 2]. Withresize = FALSE,aperm()keeps the original dimensions and drops the dimnames, so leave the default in place unless you want that. - With named dimnames,
permcan be given as character names rather than positions, which is easier to read in analysis scripts.
Step 7. Summarise over a dimension
- 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 - 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 - To build arrays from two vectors,
outer()(or%o%) returns an array whose dimensions are the concatenation of the dimensions of its two arguments, soouter(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.
dimnamesmust be a list with one component per dimension; the manual states that anything else is ignored. - A slice lost a dimension. This is
drop = TRUEat work. Usedrop = FALSEto 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. Checkdim()first. - A character index finds nothing. Character indexing needs dimnames, never partially matches, and an empty string or
NAmatches 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
- R Core Team: array (Multi-way Arrays), R reference manual, checked 2026-11-17
- R Core Team: aperm (Array Transposition), R reference manual, checked 2026-11-17
- R Core Team: Extract (Extract or Replace Parts of an Object), R reference manual, checked 2026-11-17
- R Core Team: An Introduction to R (sections on arrays), CRAN, checked 2026-11-17
- The Comprehensive R Archive Network, checked 2026-11-17
- NumPy: The N-dimensional array (ndarray), checked 2026-11-17
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.
| Indexing form | Example syntax | Documented behaviour | Source page |
|---|---|---|---|
| One index per dimension | scores["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 integers | scores[-1, , ] | Leaves the named elements or slices out of the selection | R reference: Extract |
| Numeric index matrix | x[i] where i has one column per dimension | Extracts or replaces the addressed cells; negative values not allowed, zero rows ignored, NA rows give NA | An Introduction to R, arrays; R reference: Extract |
| Character index matrix | x[m] where m is a character matrix | Works only if the array has dimnames; empty or NA indices match no name | R reference: Extract |
| drop argument | scores[, , "treated", drop = FALSE] | With drop = TRUE the result is coerced to the lowest possible dimension; applies to extraction only, not replacement | R reference: Extract |
Sources
- R Core Team: Extract (Extract or Replace Parts of an Object) (accessed 2026-11-17)
- R Core Team: An Introduction to R (accessed 2026-11-17)
- R Core Team: array (Multi-way Arrays) (accessed 2026-11-17)
Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.







