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:
Syntax
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
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")
Login to try C/C++/Java/PHP code in the editor
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
- Indexing with only two numbers, as in
arr[1, 2], which gives an error for a 3-dimensional array. - Assuming the first dimension is the number of columns, when the order is rows, columns, then layers.
- Supplying
dimwhose 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: