Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

arrays
r
communitycreator

How to obtain the length of an array in R

Onyejiaku Theophilus Chidalu

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)
Implementing the length() function

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).

RELATED TAGS

arrays
r
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring