Skip to main content
HomeAbout RLearn R

Arrays in R

Learn about Arrays in R, including indexing with examples, along with the creation and addition of matrices and the apply() function.
Apr 2020  · 8 min read

An array is a data structure that can hold multi-dimensional data. In R, the array is objects that can hold two or more than two-dimensional data. For example, in square matrices can contain two rows and two columns and dimension can take five. Arrays can store the values having only a similar kind of data types. The data can be more than one dimensional, where there are rows and columns and dimensions of some length.

Creation of an Array

The array() function will create an array which takes a vector, which is the numbers and dimension('dim') in the argument.

Let's see an example below where two vectors named 'array1' and array2' are created.

vector1 =  c (5, 10, 15,20)
vector2 =  c (25, 30, 35, 40, 45, 50,55,60)

You can take two vectors above as an input to an array where the dimension is considered as 4 * 4, and two matrices or dimensional data is created.

final = array (c (array1, array2),dim =c(4,4,3))
print (final)

The output of the above code is below :

, , 1

     [,1] [,2] [,3] [,4]
[1,]    5   25   45    5
[2,]   10   30   50   10
[3,]   15   35   55   15
[4,]   20   40   60   20

, , 2

     [,1] [,2] [,3] [,4]
[1,]   25   45    5   25
[2,]   30   50   10   30
[3,]   35   55   15   35
[4,]   40   60   20   40

, , 3

     [,1] [,2] [,3] [,4]
[1,]   45    5   25   45
[2,]   50   10   30   50
[3,]   55   15   35   55
[4,]   60   20   40   60

Let's rename our array to "Arr1" and "Arr2" by using "matrix.names".Also,the rows name changed to ("row1","row2") and column names will be changed to ("column1","column2","column3") respectively.The dimension of the matrix is 2 rows and 3 columns.

array1 =  c (9 , 18 )
array2 = c (27,36)
r.names = c ("column1","column2","column3")
c.names = c ("row1","row2")
m.names = c ("Arr1", "Arr2")

final = array (c (array1,array2), dim=c (2,3,2), dimnames=list (c.names, r.names, m.names))
print(final)

The output of the above code is below, where there are two rows and three columns. Also, the value in the column gets repeated when once it is finished:

, , Arr1

     column1 column2 column3
row1       9      27       9
row2      18      36      18

, , Arr2

     column1 column2 column3
row1      27       9      27
row2      36      18      36

Indexing in an Array

An array consists of elements in a multi-dimensional manner where each element can be accessed for the operation. The elements can be indexed by using '[]' wherein the array-like matrices consists of rows and columns which can be indexed by: mat[row, column]

Let's take an example below where the array contains vector input from 1 to 9.There are only three rows and columns where the value is from 1 to 9 is included.The 'c.names)' is the new column name which have vectors ('c1', 'c2', 'c3') and 'r.names' is the new row names ('r1', 'r2', 'r3') which is also the vector.

a1=  c (1,2,3,4)
a2= c (5,6,7,8,9)
r.names = c ("c1","c2","c3")
c.names = c ("r1","r2","r3")
m.names = c ("first")

arr = array (c (a1,a2), dim=c (3,3,1), dimnames=list (c.names, r.names, m.names))
print(arr)
, , first

   c1 c2 c3
r1  1  4  7
r2  2  5  8
r3  3  6  9

The output of the above code is below:

 , , first

   c1 c2 c3
r1  1  4  7
r2  2  5  8
r3  3  6  9 

You can see the matrices from 1 to 9 are generated with 3 3 dimension(row column) form, and the names of rows and columns are changed.

Let's see how the elements in the array can be extracted with the following examples.

  1. Let's extract number '7' from the above array 'arr'.
arr[1,3,1]

7

The output to the above code is 7.Inside of 'arr[1,3,1]' row 1 with column 3 and 1 is the first array 'arr'is extracted.

  1. To access 1, 'arr[1,1,1]' row 1 with column 1 and 1 is the first array 'arr'is extracted.
arr[1,1,1]

1

The output to the above code is 1.

  1. To access multiple values at once, you need to specify the range you want.
arr[1:2,1:2,1]
  c1 c2
r1 1 4
r2 2 5

The above code gives the output as below where the value containing 2 rows, 2 columns and 1 is the first array 'arr' is extracted:

    c1    c2
r1    1    4
r2    2    5 
  1. You can access the entire array 'arr' with the following syntax where 'arr[ , ,1]' specifies to include all rows and columns each separated by commas, which are indicated by space. The 1 specifies the array 'arr' to be extracted.
arr[ , ,1]
  c1 c2 c3
r1 1 4 7
r2 2 5 8
r3 3 6 9

The above code gives the output as below where all the elements are present:

    c1    c2    c3
r1    1    4    7
r2    2    5    8
r3    3    6    9 
  1. You can get the entire second row by following code where arr[2, ,1] gets the second row with space, and 1 is the 'arr' to be extracted.
arr[2,,1]
c1
2
c2
5
c3
8

The above code gives the output as below and also prints c1,c2,c3.

c1 2
c2 5
c3 8
  1. You can get the entire second column by following code where arr[,2,1] space with 2 is the second column, and 1 is the 'arr' to be extracted.
mat[ ,2,1]
r1
4
r2
5
r3
6

The above code gives the output as below and also prints r1,r2,r3.

r1 4
r2 5
r3 6

Matrix Creation and Addition

Let's create a matrix named mat1 and mat2 from 'arr[ , ,1]' where the entire rows and columns from 'arr' get copied.

mat1 = arr[,,1]
mat2 = arr[,,1]
   c1 c2 c3
r1  2  8 14
r2  4 10 16
r3  6 12 18 

Add two matrices 'mat1' and 'mat2' and store the result in final. The output is also printed.

final <- mat1+mat2
print(final)

The output below shows that each row and columns of mat1 and mat2 are added to one another.

   c1 c2 c3
r1  2  8 14
r2  4 10 16
r3  6 12 18 

apply()

'apply()' is one of the R packages which have several functions that helps to write code in an easier and efficient way. You'll see the example below where it can be used to calculate the sum of two different arrays.

The syntax for apply() is :
apply(x, margin, function)

The argument above indicates that:
x: An array or two-dimensional data as matrices.
margin: Indicates a function to be applied as margin value to be c(1) for rows, c(2) for columns, and c(1,2) for both rows and columns.
function: Indicates the R- built-in or user-defined function to be applied over the given data.

Let's create a vector named 'array1' of length three and 'array2' of length six with the following code.

array1 = c(5,10,15)
array2 = c(15,20,25,30,35,40)

You can see below where 'array()' accepts two vectors named 'array1' and 'array2' with a dimension of 3 rows, 3 columns, and 2 matrices are created and stored to 'my. Array'.

my.Array <- array(c(array1,array2),dim = c(3,3,2))
print(my.Array)
, , 1

     [,1] [,2] [,3]
[1,]    5   15   30
[2,]   10   20   35
[3,]   15   25   40

, , 2

     [,1] [,2] [,3]
[1,]    5   15   30
[2,]   10   20   35
[3,]   15   25   40

The above code gives the following output, where two matrices are created with the 3 3 (rows columns).

, , 1

     [,1] [,2] [,3]
[1,]    5   15   30
[2,]   10   20   35
[3,]   15   25   40

, , 2

     [,1] [,2] [,3]
[1,]    5   15   30
[2,]   10   20   35
[3,]   15   25   40

'apply()' is used below to calculate the sum of the two matrices by column-wise.

final <- apply(my.Array, c(2), sum)
print(final)
[1]  60 120 210

You can see above where c(2) for margin is used where the elements of the matrix in 'my. Array' is summed by column-wise to get the following output.

60 120 210

Finally, 'apply()' is used below to calculate the sum of the two matrices by row-wise.

final <- apply(my.Array, c(1), sum)
print(final)
[1] 100 130 160

You can see above where c(1) for margin is used where the elements of the matrix in 'my. Array' is summed by row-wise to get the following output.

100 130 160

Congratulations

Congratulations, you have made it to the end of this tutorial!

You've learned about R's Array along with its creation, indexing in an array with examples, also with creation and addition of matrices along with the apply() function.

If you would like to learn more about R, take DataCamp's Introduction to R course.

References:
R-Arrays
R Array Function and Create Array in R

R Courses

Introduction to R

BeginnerSkill Level
4 hr
2.6M
Master the basics of data analysis in R, including vectors, lists, and data frames, and practice R with real data sets.
See DetailsRight Arrow
Start Course
See MoreRight Arrow
Related

Free Access Week | Aug 28 – Sept 3

Access DataCamp's entire platform for free, including all 440+ courses, for an entire week. No catch, no credit card required—just unlimited learning for anyone with internet access.

Will Rix

5 min

How to Choose The Right Data Science Bootcamp in 2023 (With Examples)

Learn everything about data science bootcamps, including a list of top programs to kickstart your career.
Abid Ali Awan's photo

Abid Ali Awan

10 min

DataCamp Portfolio Challenge: Win $500 Publishing Your Best Work

Win up to $500 by building a free data portfolio with DataCamp Portfolio.
DataCamp Team's photo

DataCamp Team

5 min

A Data Scientist’s Guide to Signal Processing

Uncover actionable insights hidden in complex signal data by filtering noise, choosing appropriate visualizations, finding patterns in the time- and frequency-domain, and more using signal processing.
Amberle McKee's photo

Amberle McKee

25 min

Chroma DB Tutorial: A Step-By-Step Guide

With Chroma DB, you can easily manage text documents, convert text to embeddings, and do similarity searches.
Abid Ali Awan's photo

Abid Ali Awan

10 min

Introduction to Non-Linear Model and Insights Using R

Uncover the intricacies of non-linear models in comparison to linear models. Learn about their applications, limitations, and how to fit them using real-world data sets.

Somil Asthana

17 min

See MoreSee More