I am trying to combine vectorization and recursion in this implementation of the factorial function:
fac <- function(n) {
ifelse(n == 1, 1, n * fac(n-1))
}
fac(6) #720
fac(c(6,7)) #Error: evaluation nested too deeply: infinite recursion / options(expressions=)?
#Error during wrapup: evaluation nested too deeply: infinite recursion / options(expressions=)?
Although ifelse is the vectorized version of if this doesn't work (see errors).
My question
1. Why doesn't it work?
2. How can I make it work?
Edit: I don't really see the connection to the proposed duplicate because the above function doesn't even work for a vector of two!
Let's look what happens:
fac <- function(n) {
ifelse(n == 1, 1, {message(paste(n-1, collapse = ","));
stopifnot(n > 0); n * fac(n-1)})
}
fac(4:5)
#3,4
#2,3
#1,2
#0,1
#-1,0
# Show Traceback
#
# Rerun with Debug
# Error: n > 0 are not all TRUE
As you see, the condition is never TRUE
for all elements of n
and thus, recursion never stops.
If all elements of n
are equal, it works:
fac(c(5,5))
#4,4
#3,3
#2,2
#1,1
#[1] 120 120
With a small adjustment your function can work for unequal elements of n
, too:
fac <- function(n) {
ifelse(n <= 1, 1, n * fac(n-1))
}
fac(1:5)
#[1] 1 2 6 24 120
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With