Length in R: How to Find Length of an Object in R

Finding the length of vectors, factors, arrays, or lists is a common operation. In this article, we will see how to find the length of R objects in R.

Length in R

To get or set the length of vectors, lists,  factors, or other objects in R, use the length() method.

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

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, length returns NA.

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

Find Length of List in R

To find the length of the list in R, use the length() function.

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 element of the list. 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.

Find Length of String in R

To find the length of the string in R, use the nchar() function.

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

The length() function can be used for all R objects. For an environment, it returns the object number in it. NULL returns 0. Most other objects return length 1.

That is it for length() function in R.

Leave a Comment