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 variablemyarray <- c(1:10)# creating a multidimensional array using the array() functionmultiarray <- array(myarray, dim = c(3,2))# to obtain the length of the array using the length functionlength(multiarray)
Explanation
- Line 2: We create an array variable
myarraywith its elements starting from1to10. - Line 5: Using the
array()function, we create a 3x2 dimensional arraymultiarray. - Line 8: Using the
length()function, we check for the length of the arraymultiarray.
Note: The output of the code
6is obtained from the dimensions of the array (3 * 2 = 6).