How to Create an Empty Vector in R

Here are six methods to create an empty Vector in R:

  1. Using vector() function
  2. Use c() function
  3. Using numeric() function
  4. Using character() function
  5. Using rep() function
  6. Assigning NULL to an existing vector

Method 1: Using vector()

The easiest way to create an empty vector is to use the plain vector() function without arguments.

Visual Representation of using the vector() method

rv <- vector()

rv 

Output

logical(0)

To check the length of the vector, use the “length()” method.

rv <- vector()

vec(rv)

Output

[1] 0

You can add new elements to the vector:

rv <- vector()

length(rv)

cat("After adding elements to an empty vector", "\n")

rv <- c(1:7)

rv

length(rv)

Output

[1] 0
After adding elements to an empty vector
[1] 1 2 3 4 5 6 7
[1] 7

Method 2: Using c()

Using the c() method

Assing the c() function without any arguments to a variable, and that variable becomes an empty vector, as you can see in the above figure.

rv <- c()
rv

cat("length of rv : ", length(rv), "\n")

is.null(rv)

Output

NULL
length of rv : 0
[1] TRUE

Method 3: Using numeric()

Pass 0 to the numeric() function, and it returns an empty vector.

Using the numeric() method

vec <- numeric(0)

vec

cat("length of vec: ", length(rv), "\n")

Output

numeric(0)
length of rv : 0

Method 4: Using character( )

If you want to create an empty character vector, use the character() function and pass 0.

Using the character( ) method

vec <- character()

print(rv)

typeof(rv)

Output

character(0)
[1] "character"

Method 5: Using rep()

You can use the rep() function and pass two arguments: NULL and 0. The rep() function replicates the values in the input data. Therefore, it is a generic function.

Using the rep() method

rv <- rep(NULL, 0)

rv

cat("length of rv : ", length(rv), "\n")

Output

NULL
length of rv : 0

Here, you can use the is.null() function to check if the vector is NULL or not. It returns a boolean vector that is either TRUE or FALSE.

Let’s replicate NA values using the rep() function.

rv <- rep(NA, 0)

rv

length(rv)

is.null(rv)

Output

logical(0)
[1] 0
[1] FALSE

Method 6: Assigning NULL to an existing vector

If you assign any vector to a “NULL” value, it will become empty of NULL type.

Assigning NULL to an existing vector

rv <- 1:5
rv
length(rv)

rv <- NULL
rv
length(rv)
is.null(rv)

Output

[1] 1 2 3 4 5
[1] 5

NULL

[1] 0
[1] TRUE

That’s it!

1 thought on “How to Create an Empty Vector in R”

Leave a Comment