What is length() Function in R (4 Examples)

The length() function in R returns the size of an object. For example, if you have a vector x with 5 elements, the length(x) function will return 5.

Syntax

length(data)

Parameters

The length() function accepts data as a required parameter that can be either vector, factor, list, or other objects.

Return Value

The length() function returns the size of an R object.

Example 1: How to find a length of a vector in R

rv <- 1:5
print("The length of the rv is: ")
print(length(rv))

Output

[1] "The length of the rv is: "
[1] 5

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

Example 2: How to Set Vector Length in R

To set a vector length, use the assignment operator (<-) and assign the variable’s new length.

rv <- 1:5
print("The length of the rv is: ")
print(length(rv))

length(rv) <- 9
print("The new length of rv is: ")
print(length(rv))

Output

[1] "The length of the rv is: "
[1] 5
[1] "The new length of rv is: "
[1] 9

Example 3: How to find the length of the list in R

To find the length of the list in R, use the length() function. The length() function accepts a list as an argument and returns the length of the list.

rl <- list(c(1, 2, 3, 4))
print(rl)
print(length(rl))

Output

[[1]]
[1] 1 2 3 4

[1] 1

From the output, you can see that we did not get the length of each list element. It returns the number of entries on our list. If you want to get the length of a single list element, use the following code.

rl <- list(c(1, 2, 3, 4))
print(rl)
print(length(rl[[1]]))

Output

[[1]]
[1] 1 2 3 4

[1] 4

Now, you can see that the total element of the list is 4.

Example 4: How to find a length of String in R

To find a length of a string in R, use the nchar() function. The length() function accepts a string as an argument and returns the length of the string.

str <- "Yello, by Homer Simpson"

nchar(str)

Output

[1] 23

The nchar() function can be used to get the length of a string.

You can also use the length() function, but the output will differ from the above.

str <- "Yello, by Homer Simpson"

length(str)

Output

[1] 1

Conclusion

To get the length of vectors, listsfactors, or other objects in R, use the length() method. The length() function can be used for all R objects. NULL returns 0. Most other objects return length 1.

Leave a Comment