A vector is a sequence of data elements of the same basic type. A vector whose length is zero is known as an empty vector. You can create an empty vector using the c(), vector(), rep(), and numeric() function. This guide shows different ways to create an empty vector in R.
Method #1: Create an empty vector using the c() function
The combine or c() function in R is used to create vectors by combining multiple values. To create an empty vector using the c() function, do not pass anything inside the parentheses.
Syntax
vector name <- c()
Here, “vector name” can be any name you want to give to the empty vector.
Example
x <- c()
x
Output
NULL
In the above example, the output is NULL which denotes that the vector is empty.
Method #2: Create an empty vector using the vector() function
To create an empty vector using the vector() function, do not pass anything inside the parentheses.
Syntax
vector name <- vector()
Here, “vector name” can be any name you want to give to the empty vector.
Example
v <- vector()
v
Output
logical(0)
In the above example, logical(0) denotes an empty vector.
Method #3: Create an empty vector using a NULL object
You can assign NULL to an existing or a new vector to create an empty vector.
Example
If you have a vector x = c(1, 2, 3), you can convert it into an empty vector using the following code:
x <-c(1,2,3,5)
#converting to an empty vector
x <- NULL
x
Output
NULL
In the above example, we converted an existing non-empty vector to an empty vector by assigning the NULL object.
Method #4: Create an empty vector using the rep() function
rep() function in R repeats the specified object a specified number of times. It is used to create a vector with a specified number of entries. To create an empty vector using the rep() function, do not pass anything inside the parentheses.
Syntax
vector name <- rep()
Here, “vector name” can be any name you want to give to the empty vector.
Example
y <- rep()
y
Output
NULL
Method #5: Create an empty vector using the numeric() function
The numeric() function creates a numeric vector of a defined length. To create an empty vector using the numeric() function, do not pass anything inside the parentheses.
Syntax
vector name <- numeric()
Here, “vector name” can be any name you want to give to the empty vector.
Example
a <- numeric()
a
Output
numeric(0)