How to Solve R Error: replacement has length zero

by | Programming, R, Tips

This error occurs when you try to replace a value in a vector with a value of length zero. A value of length zero does not exist is the same as saying the value does not exist.

This error typically happens when trying to use the zeroth index of a vector. In R, indexes start at one, therefore the value vector[0] does not exist.

You can solve this error by ensuring you access values that exist in the vector, in other words, values with indexes starting from 1.

This tutorial will go through the error and how to solve it with code examples.


Example: Fibonacci Sequence in R

Let’s attempt to print the first ten Fibonacci numbers in R. First we will define the function

fib <- function(n){
  fib <- vector()
  fib[1] <- 1
  fib[2] <- 1
  for(i in 2:n){
    fib[i] <- fib[i-1] + fib[i-2]
  }
  return(fib)
}

Next, we will try to get the first ten fibonacci numbers:

fib(10)
Error in fib[i] <- fib[i - 1] + fib[i - 2] : replacement has length zero

The error occurs because we are trying to add a value to the fib vector that does not exist.

Arrays in R start with index 1, not 0. Therefore, at the first iteration of the for loop where i = 2, we have:

fib[2] <- fib[2-1] + fib[2 - 2], which is:

fib[2] <- fib[1] + fib[0]

There is no value at fib[0], therefore R raises the error: replacement has length zero

Solution

We can solve the error by starting the for loop at 3 instead of 2. Therefore at the first iteration of the for loop where i = 3, we have:

fib[3] <- fib[3-1] + fib[3 -2], which is

fib[3] <- fib[2] + fib[1], giving

fib[3] <- 1 + 1.

Let’s look at the revised function:

fib <- function(n){
  fib <- vector()
  fib[1] <- 1
  fib[2] <- 1
  for(i in 3:n){
    fib[i] <- fib[i-1] + fib[i-2]
  }
  return(fib)
}

Let’s run the code to get the first ten Fibonacci numbers:

fib(10)
 [1]  1  1  2  3  5  8 13 21 34 55

Summary

Congratulations on reading to the end of this tutorial!

For further reading on R related errors, go to the articles: 

Go to the online courses page on R to learn more about coding in R for data science and machine learning.

Have fun and happy researching!

Profile Picture
Senior Advisor, Data Science | [email protected] | + posts

Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.

Buy Me a Coffee