How to loop through array items using a for loop in R

Overview

An array in R is a data structure that can store multi-dimensional data of the same type in a single variable. The array object can hold two or more than two-dimensional data.

What is a for loop in R?

To understand what a for loop is in R, click here.

How to use the for loop

We can loop through the items of an array by using for loop. Let’s check out the example below:

Example

# creating an array variable
myarray <- c(1:10)
# creating a multidimensional array
multiarray <- array(myarray, dim = c(3, 2))
# using a for loop
for(x in multiarray){
print(x)
}

Explanation

  • Line 2: We create an array variable myarray with its elements ranging from 1 to 10.
  • Line 5: Using the array() function, we create a 3x2 dimensional array multiarray.
  • Line 8: Using a for loop we make reference to all the elements present in the multiarray.
  • Line 9: We print all the elements of the multiarray.

Free Resources