Create a two-dimensional array of sequence of even integers in R
In this article, we will discuss how to create a 2D array of sequences of even integers in R Programming Language.
Method 1 : Using seq() method
The array() method can be used to create an array with >=1 dimensions. This method returns an array with the extents specified in the dim attribute. For a two-dimensional array, the dim attribute contains a vector of two elements, first indicating the number of rows and then the number of columns respectively.
Syntax: array(data , dim)
- data – The data to fill into the array
- dim – The dimensions of the matrix in the form of vector
The data in this method can be created using the seq() method, which is used to generate regular sequences, within the defined range of numbers.
Syntax: seq(from = 1, to = 1, length.out , by = ((to – from)/(length.out – 1))
- from, to – (Default : 1) The starting and (maximal) end values of the sequence.
- by – Indicator of the number to increment the sequence by.
- length.out – A non-negative integer indicator of the length of the sequence.
In this approach, the from attribute must be even in order to generate a sequence of even integers. The length.out argument will be equal to the product of dimensions of the 2-D matrix. And by attribute holds a value of 2, to increment the number by 2 each time.
 "Array of even integers sequence:" [,1] [,2] [,3] [1,] 2 10 18 [2,] 4 12 20 [3,] 6 14 22 [4,] 8 16 24
Method 2: Manually using for loop
The starting position to begin the sequence of data is specified along with the desired dimensions of the 2-D array. Since the total number of required elements is equal to the product of dimensions, but here we need even numbers that occur at alternate positions. So, the total number of elements will be equivalent to double the product of dimensions. Now, the ending position is given by :
ending_position = starting_position + number of elements
A for loop is started to iterate from the starting position to ending position-1 to generate a sequence of elements within this range, and whenever an even number is encountered, the number is appended to an empty list. This vector forms the sequence of even integers and can be fed to the matrix() method of base R, which creates a 2D matrix.
matrix (data , nrow = )
Time complexity can be assumed to be nearly constant until very large dimensional sizes.
 "Sequence of even integers in 2-D array" [,1] [,2] [1,] 20 26 [2,] 22 28 [3,] 24 30