*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.*

## Table of contents

## 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:

- How to Solve R Error in sort.int(x, na.last = na.last, decreasing = decreasing, …) : ‘x’ must be atomic
- How to Solve R Error: the condition has length > 1

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!

Suf is a research scientist at Moogsoft, specializing in Natural Language Processing and Complex Networks. Previously he was a Postdoctoral Research Fellow in Data Science working on adaptations of cutting-edge physics analysis techniques to data-intensive problems in industry. In another life, he was an experimental particle physicist working on the ATLAS Experiment of the Large Hadron Collider. His passion is to share his experience as an academic moving into industry while continuing to pursue research. Find out more about the creator of the Research Scientist Pod here and sign up to the mailing list here!