R – Array

Arrays are essential data storage structures defined by a fixed number of dimensions. Arrays are used for the allocation of space at contiguous memory locations.

In R Programming Language Uni-dimensional arrays are called vectors with the length being their only dimension. Two-dimensional arrays are called matrices, consisting of fixed numbers of rows and columns. R Arrays consist of all elements of the same data type. Vectors are supplied as input to the function and then create an array based on the number of dimensions.

Creating an Array

An R array can be created with the use of array() the function. A list of elements is passed to the array() functions along with the dimensions as required.

Syntax:

array(data, dim = (nrow, ncol, nmat), dimnames=names)

where

nrow: Number of rows

ncol : Number of columns

nmat: Number of matrices of dimensions nrow * ncol

dimnames : Default value = NULL.

Otherwise, a list has to be specified which has a name for each component of the dimension. Each component is either a null or a vector of length equal to the dim value of that corresponding dimension.

Uni-Dimensional Array

A vector is a uni-dimensional array, which is specified by a single dimension, length. A Vector can be created using ‘c()‘ function. A list of values is passed to the c() function to create a vector.

R

vec1 <- c(1, 2, 3, 4, 5, 6, 7, 8, 9) 
print (vec1) 

# cat is used to concatenate 
# strings and print it. 
cat ("Length of vector : ", length(vec1))