How to Create Empty Vector in R

Manav Narula Feb 02, 2024
  1. Use the vector() Function to Create an Empty Vector in R
  2. Use the numeric() Function to Create a Numeric Empty Vector in R
How to Create Empty Vector in R

A Vector is one of the fundamental data structures in R. It is used to store elements in a sequence, but unlike lists, all elements in a vector must be of the same data type. Based on the type of data stored in a vector, we can classify it into Numerical, Logical, Integer, DateTime, Factors, and Character Vectors.

In R programming, we can create a Vector using a few built-in functions.

Use the vector() Function to Create an Empty Vector in R

The vector() function in R is used to create a vector of the specified length and type specified by length and mode. The mode by default is logical but can be changed to numeric, character, or even to list or some expression.

An example to create an empty Vector is shown below:

vec <- vector()

Use the numeric() Function to Create a Numeric Empty Vector in R

We can use the numeric() function to create Numeric Vectors in R. We can also pass the length of the vector as its argument.

An example to create an empty Numeric Vector is shown below:

vec2 <- numeric()
Note

Similarly, we can also use the character() or logical() function to create empty vectors of Character and Logical type and specify its length using the length argument. We can check whether an object is a vector or not using is.vector() function, which returns True for vector objects, as shown below:

> is.vector(vec2)
[1] TRUE
Author: Manav Narula
Manav Narula avatar Manav Narula avatar

Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.

LinkedIn

Related Article - R Vector