Get the length of vectors in R

R introduction Structure exploration
Get the length of a vector in R

The length function returns the length of R objects while lengths returns the length for each element of an R object. In this tutorial we will review with several examples use cases of these functions.

length()

The length function returns the length of vectors, lists and factors, as well as the number of columns of data frames and the number of elements of a matrix.

x <- c(4, 1, 6, 2)
length(x)
4

For a list, the function returns the number of elements of that list, not taking into account the length of each of the elements.

l <- list(a = 1:3, b = 8:15)
length(l)
2

For a data frame, the function returns the number of columns.

df <- iris
length(df)
5

For a matrix, the function returns the number of elements of that matrix, this is, the number of columns multiplied by the number of rows.

m <- as.matrix(iris)
length(m)
750

The function can also be used to set the length of an object. In the following example we increase the size of the sample vector, so NA are added to the original vector to match the new desired length.

x <- c(4, 1, 6, 2)
length(x) <- 6
x
4  1  6  2 NA NA

lengths()

The lengths function is similar to length but it returns the length for each element of the input. Recall the example of the list with two elements of different length. The lengths function will return the length of each of the elements of the list.

l <- list(a = 1:3, b = 8:15)
lengths(l)
a b 
3 8

Note that this function provides an argument named use.names which can be set to FALSE in order to remove the names from the input.

l <- list(a = 1:3, b = 8:15)
lengths(l, use.names = FALSE)
3 8