length()
length(x) Returns:
integer · Updated March 13, 2026 · Base Functions base vector length
The length() function returns the number of elements in a vector, the number of components in a list, or the length of a string. It is one of the most frequently used functions in R for determining the size of objects. You can also use length<- to assign a new length to an object, which is useful for truncating or extending vectors.
Syntax
length(x)
length(x) <- value
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
x | any R object | N/A | A vector, list, matrix, data frame, or other R object |
value | non-negative integer | N/A | New length to assign (only when using length<-) |
Examples
Basic usage with vectors
# Numeric vector
x <- c(1, 2, 3, 4, 5)
length(x)
# [1] 5
# Character vector
words <- c("apple", "banana", "cherry")
length(words)
# [1] 3
# Empty vector
empty <- character(0)
length(empty)
# [1] 0
Working with lists
my_list <- list(a = 1, b = 2, c = 3)
length(my_list)
# [1] 3
# Nested list
nested <- list(list(1, 2), list(3, 4, 5))
length(nested)
# [1] 2
Setting length
x <- 1:10
length(x)
# [1] 10
# Truncate to 5 elements
length(x) <- 5
x
# [1] 1 2 3 4 5
# Extend to 10 elements (fills with NA)
length(x) <- 10
x
# [1] 1 2 3 4 5 NA NA NA NA NA
Common Patterns
Looping over elements:
for (i in 1:length(x)) {
print(x[i])
}
Checking if a vector is empty:
if (length(x) == 0) {
message("Vector is empty")
}
Dynamic vector growth (inefficient - pre-allocate instead):
result <- numeric(0)
for (i in 1:100) {
length(result) <- i
result[i] <- i^2
}