R: Create vector of zeros

Vector of zeros is sometimes required to initialize a vector with values or neutralize it after performing a few operations.

In this article, we will be creating a vector of zeros using different ways.

R : Create a vector of zeros using integer () function

The integer() function in R creates objects of vectors (integer) of specified length in the argument where each element of the vector is equal to zero.

Syntax :  integer (length)
Arguments:  length – represents the length of the vector created.

Let us understand with an example.

Example: –
In the below code example, we are creating a vector of zeros; length 5.

vector_of_zero = integer(5)
cat(" vector created with integer()function : " , vector_of_zero , "\n")

Output :-

vector created with integer()function : 0 0 0 0 0

R : Create a vector of zeros using the numeric() function

In R, the numeric() function creates objects of numeric type. The numeric() function will create a double-precision vector of the specified length in the argument with all elements value equal to zero.

Syntax :  numeric (length)
Arguments:  length – represents the length of the vector created.It should be non-negative.

Let us understand with an example.

Example:-

In the below code example, we are creating a vector of zeros; length 5.

vector_of_zero = numeric(5)
cat(" vector created with numeric()function : " , vector_of_zero , "\n")

Output :-

vector created with numeric()function :  0 0 0 0 0

R : Create a vector of zeros using the rep() function

In R, the rep() function replicates the value of the vector and lists.

Syntax : rep(x, times).
Arguments : x – represents a vector or a factor ; times – represents the number of times each element of the vector to be repeated or repeat full vector if it is of length 1.

Let us understand with an example.

Example:-

In the below code example, we are creating a vector of zeros; length 5.

vector_of_zero = rep(0, 5)
cat(" Vector created with rep()function : " , vector_of_zero , "\n")

Output :-

Vector created with rep()function :  0 0 0 0 0