← Back to R Course | Chapter 7: Data Structures | Lesson 5 of 7

Arrays

An array is like a matrix that can have more layers, like a stack of trays or a cube of cubbies. It lets you store data in three or more directions.

In this page:

  1. Arrays
Syntax
r
array_name <- array(data, dim = c(rows, cols, layers))
array_name[row, col, layer]

Arrays

An R array generalizes a matrix to more than two dimensions, storing data in a multi-dimensional grid with array(data, dim = c(...)).

Elements are accessed by specifying an index for each dimension, like a[1, 2, 3]. Arrays are less commonly used than matrices or data frames but are useful for genuinely multi-dimensional data.

Note: A 2-dimensional array is functionally the same as a matrix -- matrix() is just a convenient special case.

Example: Arrays

markup
arr <- array(1:24, dim = c(2, 3, 4))

cat("Dimensions:", dim(arr), "\n")
cat("Element at [1,2,3]:", arr[1, 2, 3], "\n")
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Indexing with only two numbers, as in arr[1, 2], which gives an error for a 3-dimensional array.
  2. Assuming the first dimension is the number of columns, when the order is rows, columns, then layers.
  3. Supplying dim whose product does not match the data length, so values are cut or recycled.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.