# How to Fix in R: replacement has length zero

One error you may encounter in R is:

```Error in x = x : replacement has length zero
```

This error occurs when you attempt to replace a value in a vector with another value that “has length zero” – which means it does not exist.

This tutorial shares exactly how to fix this error.

### How to Reproduce the Error

Suppose we create the following vector with 10 values in R:

```data = c(1, 4, 5, 5, 7, 9, 12, 14, 15, 17)
```

Now suppose we attempt to use the following for() loop to multiply each value in the vector by the value that comes before it:

```for (i in 1:length(data)) {
data[i] = data[i] * data[i-1]
}

Error in data[i] <- data[i] * data[i - 1] : replacement has length zero
```

We receive the error “replacement has length zero” because during the first loop we attempt to perform the following multiplication:

• data * data

Since R indexes start at 1, the value data simply does not exist.

We can verify this by attempting to print the value located at position 0 in the vector:

```print(data)

numeric(0)
```

The result is a numeric vector of length 0 – in other words, it doesn’t exist.

### How to Fix the Error

The way to fix this error is to simply use a for() loop that doesn’t attempt to access a value in the vector that doesn’t exist.

In our example, we could fix this error by starting the for loop at index position 2 as opposed to position 1:

```for (i in 2:length(data)) {
data[i] = data[i] * data[i-1]
}

#view updated vector
data

         1         4        20       100       700      6300     75600
   1058400  15876000 269892000
```

Notice that we don’t receive an error because we never attempted to access an index position in the vector that doesn’t exist.