Home » How to Create a Vector of Zeros in R (With Examples)

How to Create a Vector of Zeros in R (With Examples)

by Erma Khan

There are three common ways to create a vector of zeros in R:

Method 1: Use numeric()

#create vector of 12 zeros
numeric(12)

Method 2: Use integer()

#create vector of 12 zeros
integer(12)

Method 3: Use rep()

#create vector of 12 zeros
rep(0, 12)

The following examples show how to use each method in practice.

Example 1: Create Vector of Zeros Using numeric()

The following code shows how to create a vector of zeros using the numeric() function:

#create vector of 12 zeros
numeric(12)

 [1] 0 0 0 0 0 0 0 0 0 0 0 0

The result is a vector with 12 zeros.

Note that this vector will have a class of numeric.

Example 2: Create Vector of Zeros Using integer()

The following code shows how to create a vector of zeros using the integer() function:

#create vector of 12 zeros
integer(12)

 [1] 0 0 0 0 0 0 0 0 0 0 0 0

The result is a vector with 12 zeros.

Note that this vector will have a class of integer.

Example 3: Create Vector of Zeros Using rep()

The following code shows how to create a vector of zeros using the rep() function:

#create vector of 12 zeros
rep(0, 12)

 [1] 0 0 0 0 0 0 0 0 0 0 0 0

The result is a vector with 12 zeros.

Note that this vector will have a class of numeric.

Related: How to Use rep() Function in R to Replicate Elements

Additional Resources

The following tutorials explain how to perform other common tasks in R:

How to Create a Vector with Random Numbers in R
How to Create an Empty Vector in R
How to Check if a Vector Contains a Given Element in R

Related Posts