generate the nth fibonacci number in r

To generate the nth Fibonacci number in R, we can use recursion as follows:

fibonacci <- function(n) {
  if(n == 1 || n == 2) {
    return(1)
  } else {
    return(fibonacci(n-1) + fibonacci(n-2))
  }
}
127 chars
8 lines

In this function, we first check if n is 1 or 2 - in this case, the nth Fibonacci number is simply 1. If n is greater than 2, we recursively call the fibonacci function with n-1 and n-2 as arguments and add their results together.

To find, for example, the 7th Fibonacci number, we would call the function with fibonacci(7) which would return 13.

related categories

gistlibby LogSnag