A simple cycle in R producing a “zero-length replacement” in R

I'm new to R, and so what seemed to work well in C and Python suddenly breaks in R. I'm trying to calculate the product of the first 1000 Fibonacci numbers. Here is the complete 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 that I misunderstood the work with different elements of the array (perhaps i-2 is not correct in the description of the vector), but I have not found anything over the past hour and a half that will have helped me fix this. Therefore, any understanding of the cause of the problem would be most appreciated.

Thanks in advance.

+6
source share
1 answer

Arrays in R are based on 1.

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

(balance in your question)

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

 Fibonacci[i]<-(Fibonacci[i-1])+(Fibonacci[i-2]) 
+14
source

Source: https://habr.com/ru/post/949503/


All Articles