EZ

Eduzan

Learning Hub

Back to R PROGRAMMING LANGUAGE

Length of Vectors – length() Function

Published 2025-12-13

R (programming language)

The length() function in R is a versatile tool used to determine or set the number of elements in a vector, list, or other objects. Vectors can be of various types such as numeric, character, or logical.

Getting the Length of an Object

To get the length of a vector or object, you can use the length() function.

Syntax:

length(x)

Parameters:

  • x: A vector or an object whose length you want to determine.

Example 1: Getting the Length of a Vector

# R program to illustrate length function

# Defining some vectors
a <- c(10)
b <- c(5, 8, 12, 15, 20)

# Using length() function
length(a)
length(b)

Output:

[1] 1
[1] 5

Example 2: Getting the Length of a Matrix

# Defining a matrix
matrix_obj <- matrix(
    # A sequence of numbers
    c(1, 2, 3, 4, 5, 6),

    # Number of rows
    nrow = 2,

    # Number of columns
    ncol = 3
)

print(matrix_obj)

# Finding the length of the matrix
length(matrix_obj)

Output:

[,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6

[1] 6

Example 3: Getting the Length of a Data Frame

# Defining a data frame
data <- data.frame(
    Age = c(25, 30, 35, 40, 45),
    Salary = c(50000, 60000, 70000, 80000, 90000)
)

print(data)

# Using length() function
length(data)

Output:

Age Salary
1  25  50000
2  30  60000
3  35  70000
4  40  80000
5  45  90000

[1] 2

Example 3:

# Creating a vector with mismatched intervals
incomplete_sequence = 2.1:6.9

# Printing the vector
print(incomplete_sequence)

Output:

[1] 2.1 3.1 4.1 5.1 6.1

Note: For a data frame, length() returns the number of columns (variables).

Example 4: Getting the Length of a List

# Creating a list
studentList <- list(
    StudentID = c(101, 102, 103),
    Names = c("Alice", "Bob", "Charlie"),
    Marks = c(89, 95, 78)
)

print(studentList)

# Finding the length of the list
length(studentList)

Output:

$StudentID
[1] 101 102 103

$Names
[1] "Alice"   "Bob"     "Charlie"

$Marks
[1] 89 95 78

[1] 3

Example 5: Getting the Length of a String

In R, determining the length of a string requires splitting it into individual characters first.

# Defining a string
text <- "Learning R Programming"

# Basic application of length()
length(text)

# Splitting the string and counting characters
length(unlist(strsplit(text, "")))

Output:

[1] 1
[1] 22

Setting the Length of a Vector

You can also set the length of a vector using the length() function.

Syntax:

length(x) <- value

Parameters:

  • x: A vector or object.
  • value: The desired length of the vector.

Example:

# Defining some vectors
p <- c(7)
q <- c(10, 20, 30, 40)
r <- c(1, 3, 5, 7, 9)

# Setting new lengths for the vectors
length(p) <- 3
length(q) <- 6
length(r) <- 4

# Displaying the modified vectors
p
q
r

Output:

[1]  7 NA NA
[1] 10 20 30 40 NA NA
[1] 1 3 5 7