How to Create a Vector of Zero Length in R (Example)

 

In this post, I’ll explain how to create an empty vector in R programming.

Table of contents:

Let’s dive right in:

 

Example 1: Create Empty Numeric Vector in R

In Example 1, I’ll show you how to create a numeric vector of zero length. For this task, we can use the numeric() function as follows:

vec_num <- numeric()          # Numeric vector of 0 length

The previous R code stored an empty numeric vector in the data object vec_num. Let’s print the vector to the RStudio console:

vec_num                       # Print empty vector
# numeric(0)

As you can see, the output is a numeric array with zero length.

We can double check the length of our vector by applying the length function:

length(vec_num)               # Apply length function
# 0

The RStudio console shows the length of our numeric vector (i.e. 0).

 

Example 2: Empty Vectors of Other Data Types

In Example 1 you have learned how to create an empty vector of the numeric data class. However, we can create a vector with zero length of basically any data type. The following R code creates empty factors, logicals, integers, and so on…

vec_cha <- character()        # Numeric vector of 0 length
vec_fac <- factor()           # Factor vector of 0 length
vec_log <- logical()          # Logical vector of 0 length
vec_int <- integer()          # Integer vector of 0 length
vec_dou <- double()           # Double vector of 0 length
vec_raw <- raw()              # Raw vector of 0 length
vec_com <- complex()          # Complex vector of 0 length

 

Video, Further Resources & Summary

Have a look at the following video of my YouTube channel. In the video, I’m explaining the R programming codes of this tutorial.

 

Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.

YouTube Content Consent Button Thumbnail

YouTube privacy policy

If you accept this notice, your choice will be saved and the page will refresh.

 

In addition, you might read some of the other posts of this homepage. A selection of related articles is shown below:

 

Summary: At this point you should have learned how to initialize a vector with a fixed length of zero in R. Let me know in the comments below, in case you have any additional questions.

 

Subscribe to my free statistics newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Menu
Top