get length of vector in R (shows 5 as output)

R – Get the Length of a Vector

In this tutorial, we will look at how to get the length (or size) of a vector in R with the help of some examples.

How to get the length of a vector in R?

You can use the length() function in R to get the length of a vector. Pass the vector as an argument to the function. The following is the syntax –

# length of vector, vec
length(vec)

It returns the length of the vector. You can also use the length() function to set the length of a vector (look at the examples below).

Examples

Let’s look at some examples of using the length() function in R. First, we will create a vector that we will be using throughout this tutorial.

# create a vector
vec <- c(10, 20, 30, 40, 50)
# display the vector
print(vec)

Output:

[1] 10 20 30 40 50

We now have a vector of some numbers.

Get the length of a vector with the length() function.

Let’s get the length of the vector created above using the length() function.

# get length of the vector
length(vec)

Output:

📚 Data Science Programs By Skill Level

Introductory

Intermediate ⭐⭐⭐

Advanced ⭐⭐⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

5

We get 5 as the length of the vector.

Set the length of a vector with length() function

You can also use the length() function to set (or modify) the length of a vector in R. Keep the following points in mind when setting the length for a vector –

  • If you reduce the length of a vector, the extra values in the vector will be discarded.
  • If you increase the length of a vector, the extra values will be padded by NA.

Let’s now look at some examples. First, let’s set the length of the above vector to 3 and display the resulting vector.

# set length of the vector
length(vec) <- 3
# display the vector
print(vec)

Output:

[1] 10 20 30

You can see that the vector here is shortened and the extra values (40 and 50) are removed from the vector.

Let’s now set the length of this vector to 6.

# set length of the vector
length(vec) <- 6
# display the vector
print(vec)

Output:

[1] 10 20 30 NA NA NA

You can see that the vector is elongated and is padded with NA values.

You might also be interested in –


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.


Author

  • Piyush Raj

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

Scroll to Top