# Example 7.1: Create a Fibonacci sequence

June 12, 2009
By

(This article was first published on SAS and R, and kindly contributed to R-bloggers)

The Fibonacci numbers have many mathematical relationships and have been discovered repeatedly in nature. They are constructed as the sum of the previous two values, initialized with the values 1 and 1.

A pdf of this example is available here.

SAS
In SAS, we use the lag function (section 1.4.17, p. 22) to retrieve the last value.

`data fibo;do i = 1 to 10;    fib = sum(fib, lag(fib));    if i eq 1 then fib = 1;    output;    end;run;proc print data=fibo; run;`

This generates the following output:

`Obs i fib1   1   12   2   13   3   24   4   35   5   56   6   87   7  138   8  219   9  3410 10  55`

R
In R we can loop over an array to perform the same job.

`len <- 10fibvals <- numeric(len)fibvals[1] <- 1fibvals[2] <- 1for (i in 3:len) {    fibvals[i] <- fibvals[i-1]+fibvals[i-2]} `

This generates the following output:

`> fibvals[1] 1 1 2 3 5 8 13 21 34 55`

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...