Home » How to Fix in R: replacement has length zero

How to Fix in R: replacement has length zero

by Erma Khan

One error you may encounter in R is:

Error in x[1] = x[0] : 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] 

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

  • data[1] * data[0]

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

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

print(data[0])

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]         1         4        20       100       700      6300     75600
 [8]   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.

Additional Resources

The following tutorials explain how to fix other common errors in R:

How to Fix: the condition has length > 1 and only the first element will be used
How to Fix: replacement has X rows, data has Y
How to Fix: non-numeric argument to binary operator
How to Fix: dim(X) must have a positive length
How to Fix: error in select unused arguments

Related Posts