When doing data science, it is sometimes necessary to set up variables in advance, this is particularly true of vectors and data frames. This is because you may need to add data one piece at a time but keep the same vector length.

## Multiple Ways to Create a Vector of Zeros in R

There are four different functions that you can use to create a vector of zeros. They are the standard vector function, rep function, numeric function, and integer function. Visually the results look the same, but they produce different types of numeric vectors. Using a long integer in the rep function produces a fifth type of numeric variable. This gives you the ability to set up vectors of different value types. Each of these types has different properties with a variety of uses.

## How this works…

Except in the rare situation where you may actually have data consisting entirely of zeros, such a vector is going to be used as a placeholder for adding values later on. This is actually quite common in computer programming where you have a user entering data. In such cases, you need to have the proper variables set up in advance without necessarily knowing what the content is going to be other than the data type.

## Examples

Here are examples of six different methods for making a vector of zeros.

> x = c(0, 0, 0, 0, 0, 0, 0)

> x

[1] 0 0 0 0 0 0 0

Here we use the standard method of declaring a vector, the function is simply filled with zeros.

> x = rep(0, 7)

> x

[1] 0 0 0 0 0 0 0

In this example, we use the rep function using zero and the number of times we want it repeated.

> x = rep(0L, 7)

> x

[1] 0 0 0 0 0 0 0

In this example, we use the rep function with a long integer zero and the number of times we want it repeated.

> x = numeric(7)

> x

[1] 0 0 0 0 0 0 0

In this example, we use the numeric function to specify a numeric vector of a specific length.

> x = integer(7)

> x

[1] 0 0 0 0 0 0 0

In this final example, we use the integer function to specify an integer vector of a specific length.

## How To Use This In the Real World

The primary application of a vector of zeros is going to be a placeholder for future data entry. One common situation where such a placeholder is useful is when you have a user entering data into the program, but you need to have the vector set up in advance so that you have a place to put each value as it is entered. Another situation where placeholders are useful is when the data needs to be calculated and placed into the vector after each round of calculations.

A vector of zeros comes in handy as a placeholder for any time you need to enter values one at a time. This makes it a helpful tool to have in your programming toolbox.