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:
Highlighted programs for you
Flatiron School
Flatiron School
University of Maryland Global Campus
University of Maryland Global Campus
Creighton University
Creighton University
[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:
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.