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 variablemyarray <- c(1:10)# creating a multidimensional arraymultiarray <- array(myarray, dim = c(3, 2))# using a for loopfor(x in multiarray){print(x)}
Explanation
- Line 2: We create an array variable
myarraywith its elements ranging from1to10. - Line 5: Using the
array()function, we create a 3x2 dimensional arraymultiarray. - Line 8: Using a
forloop we make reference to all the elements present in themultiarray. - Line 9: We print all the elements of the
multiarray.