Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple for loop in R producing "replacement has length zero" in R

Tags:

for-loop

r

I am a novice in R, and so what seemed to work fine in C and Python, surprisingly breaks down in R. I am trying to calculate the product of the first 1000 Fibonacci numbers. Here is the full code:

#PRRODUCT OF FIBONACCI NUMBERS
Fibonacci<-rep(0, 1000)
Fibonacci[0]<-1
Fibonacci[1]<-1
Product<-1

for (i in 2:1000)
{
    Fibonacci[i]<-(Fibonacci[i-1])+(Fibonacci[i-2])
    Product<-Fibonacci[i]*Product
}

Fibonacci[1000]
Product

This returns the following error:

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

I am inclined to think I have misunderstood operating with different elements of an array (perhaps the i-2 in the vector description is not correct), but I haven't found anything over the past hour and a half which would have helped me correct it. So, any insights into the cause of the problem would be most appreciated.

Thank you in advance.

like image 511
user2585222 Avatar asked Jul 15 '13 22:07

user2585222


1 Answers

Arrays in R are 1-based.

Fibonacci[1]<-1
Fibonacci[2]<-1
Product<-1
for (i in 3:1000)
{

(the remainder as in your question)

The problem is Fibonacci[0] which is a 0-length numeric. When i = 2, this expression has a right hand side of numeric(0):

Fibonacci[i]<-(Fibonacci[i-1])+(Fibonacci[i-2])
like image 180
Matthew Lundberg Avatar answered Sep 22 '22 02:09

Matthew Lundberg