Create Fibonacci series
Title
Question
How to create a fibonacci series using FUNCTION?
R Functions-in-R 12-13 min 50-60 sec
Answers:
You can use recursion for this. There are some methods on the Internet:
https://www.datamentor.io/r-programming/examples/fibonacci-sequence/
https://www.datamentor.io/r-programming/examples/fibonacci-recursion/
fibonacci <- function(n) {
if (n <= 0) {
return(NULL)
} else if (n == 1) {
return(0)
} else if (n == 2) {
return(c(0, 1))
} else {
fib_series <- numeric(n)
fib_series[1] <- 0
fib_series[2] <- 1
for (i in 3:n) {
fib_series[i] <- fib_series[i - 1] + fib_series[i - 2]
}
return(fib_series)
}
}
Login to add comment