R length() Function

The length() function is used to calculate the length of vectors or any other R object.

Syntax

length(data)

Parameters

data (required): It accepts data that can be either vector, factor, list, or other objects.

Return Value

It returns the size of an R object.

Example 1: Finding the length of a vector

Length of vector

vec <- 1:5

cat("The length of vector is:", length(vec), "\n")

Output

The length of vector is: 5

Here, we defined a vector that returns the length; otherwise, the length returns NA.

Example 2: Usage with a list

Finding the length of the list

main_list <- list(c(1, 2, 3, 4))

cat("The length of list is:", length(main_list), "\n")

Output

The length of list is: 1

From the output, you can see that we did not get the length of each list element. Instead, it returns the number of entries on our list.

To get the length of a single list element, use this code:

main_list <- list(c(1, 2, 3, 4))

cat("The length of single list element is:", length(main_list[[1]]), "\n")

Output

The length of single list element is: 4

Length of a single list element

Example 3: Usage with a Data Frame

If you use the length() function on the data frame, it will return the number of columns in the data frame.

Finding the length of a data frame

df <- data.frame(
  col1 = c(1, 2, 3),
  col2 = c(4, 5, 6),
  col3 = c(7, 8, 9)
)

length(df)

Output

[1] 3

The length() is different from nrow() and ncol(), which return the number of rows and columns of a matrix or data frame, respectively.

Example 4: Usage with a string

If you pass a string to the length(), it will return a value of 1. 

Finding the length of a string

str <- "Krunal"

length(str)

Output

[1] 1

To count the characters of a string, you can use the “nchar()” function.

str <- "Krunal"

nchar(str)

Output

[1] 6

For multi-dimensional arrays, length() will return the total number of elements across all dimensions.

Leave a Comment