Length in R: How to Find Length of List, Vector, and String

Finding the length of vectors, factors, arrays, or lists is a common operation.

Length in R

To get the length of vectors, listsfactors, 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, the 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

How to find the length of 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 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.

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

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 the length() function in R.

Leave a Comment