R Arrays

To store data in more than two dimensions, we use Arrays in the R programming language. For this, the array() function is used. While creating an array, the dim parameter is used to set the array dimensions. In this lesson, we will learn how to create an Array and work on some operations on Arrays.

Create an Array

We will now create an array using the array() and dim. In the below example, we have taken values from 1 to 8. The dim is used to set the dimensions i.e. c(2,2,2). Let us see first what that means in the below figure:

Arrays in the R programming language

Let us now see the example to create an array in the R programming language:

Output

Iterate an Array

We can easily iterate through an array in R using the for loop. Let us see the example:

Output

Find the length of an array

The length() function is used in R to get the length of the array. Let us see an example:

Output

Above, the length of the array is 8.

Get the Number of rows and columns

The dim() function is used in R to get the number of rows and columns of an array. Let us see an example:

Output

Access array items

Use the [] brackets to access array items i.e. elements of an R array.  Just set the position number of the element you want to fetch. Follow the below syntax:

Above, the row is the position number of the rows, the column is the number of columns, and the level is the level of the matrix i.e. the 1st, 2nd, and 3rd matrix.

In the below example, we will access the items with:

  • row position 2, column position 2, and accessing the 1st matrix
  • row position 1, column position 1, and accessing the 2nd matrix:

Let us see the example to access the array items in R:

Output

Find if a specific item is present in an array

Use the %in% operator in the R programming language to find if an item i.e. element is in an array. If the item is present, TRUE is returned, else FALSE.

Let us see an example to find items in an array:

Output


If you liked the tutorial, spread the word and share the link and our website Studyopedia with others.


For Videos, Join Our YouTube Channel: Join Now


R Functions
R Vectors
Studyopedia Editorial Staff
Studyopedia Editorial Staff
[email protected]

We work to create programming tutorials for all.

No Comments

Post A Comment

Discover more from Studyopedia

Subscribe now to keep reading and get access to the full archive.

Continue reading