Suppose you're asked to write a recursive function in R that calculates the factorial of a number. How would you do it?
- factorial <- function(n) { if (n <= 1) { return(1) } else { return(n * factorial(n - 1)) } }
- factorial <- function(n) { if (n <= 1) { return(n) } else { return(n + factorial(n - 1)) } }
- factorial <- function(n) { if (n <= 1) { return(0) } else { return(n * factorial(n)) } }
- All of the above
To write a recursive function in R that calculates the factorial of a number, you can use the following code: factorial <- function(n) { if (n <= 1) { return(1) } else { return(n * factorial(n - 1)) } }. The function checks if the input n is less than or equal to 1. If it is, it returns 1 (base case). Otherwise, it multiplies n with the factorial of n - 1 (recursive case). This recursive calculation continues until the base case is reached.
Loading...
Related Quiz
- Is there a limit to how many if statements you can nest in R?
- Can you discuss how nested lists work in R and their potential use cases?
- Describe a situation where you had to use a global variable in R for a complex task. What were some of the challenges you faced, and how did you overcome them?
- How does R handle lists that contain elements of different data types?
- The ______ function in R returns the mode of an object, which is its data type.