How to obtain the length of an array in R

Overview

An array in R is a data structure that can hold multi-dimensional data of the same type stored in a single variable.

To obtain the length of an array in R, we make use of the length() function.

Syntax

length(array)

Parameters

The length() function takes a single but mandatory parameter value that represents the array object.

Return value

The length() function returns the length of a given array.

Example

# creating an array variable
myarray <- c(1:10)
# creating a multidimensional array using the array() function
multiarray <- array(myarray, dim = c(3,2))
# to obtain the length of the array using the length function
length(multiarray)

Explanation

  • Line 2: We create an array variable myarray with its elements starting from 1 to 10.
  • Line 5: Using the array() function, we create a 3x2 dimensional array multiarray.
  • Line 8: Using the length() function, we check for the length of the array multiarray.

Note: The output of the code 6 is obtained from the dimensions of the array (3 * 2 = 6).

Free Resources