Here are six methods to create an empty Vector in R:
- Using vector() function
- Use c() function
- Using numeric() function
- Using character() function
- Using rep() function
- 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.
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()
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.
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.
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.
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.
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!
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.
A buddy of mine recommended your blog on Facebook. I can see why. Great post here.