[R] Fibonacci

Petr Savicky savicky at praha1.ff.cuni.cz
Wed Apr 20 12:52:57 CEST 2011


On Wed, Apr 20, 2011 at 11:42:38AM +0200, Georgina Imberger wrote:
> Hi!
> 
> I am trying to work out the code to get a Fibonacci sequence, using the
> while() loop and only one variable. And I can't figure it out.
> 
> Fibonacci<-c(1,1)
> while (max(Fibonacci)<500){
> Fibonacci<-c(Fibonacci, (max(Fibonacci) + ?(Fibanacci)))
> }
> 
> 
> How can I tell R to take the value one before the max value? (Without
> defining another variable)

Is it allowed to use length() function? If so, then try
the following

  Fibonacci<-c(1,1)
  while (max(Fibonacci)<500){
      Fibonacci<-c(Fibonacci, Fibonacci[length(Fibonacci) - 1] + Fibonacci[length(Fibonacci)])
  }

Petr Savicky.



More information about the R-help mailing list