Search code examples
rfunctionvectorwhile-loopfactorial

Storing Answers From Functions into a Vector in R


I was prompted a question and am ever so close to solving what I need. The question is as follows-

"Write a while loop that computes and stores as a new object, the factorial of any non-negative integer mynum by decrementing mynum by 1 at each repetition of the braced code."

Another factor was that if 0 or 1 was entered, the output would be 1.

The code that I wrote as follows-

factorialcalc <- function(i){
  factorial <- 1
  if(i==0 | i==1){
    factorial <- 1
  } else{
    while(i >= 1){
      factorial <- factorial * i
      i <- i-1
    }
  }
  return (factorial)
}

with inputs-

mynum <- 5
factorialcalc(mynum)

and output-

[1] 120

You may be wondering, "your code works perfect, so what's the issue?" My issue lies in the part of the question that says "computes AND stores."

How can I modify my code to put the answers of factorialcalc into a vector?

Example- I input

mynum <- 5
factorialcalc(mynum)

and

mynum <- 3
factorialcalc(mynum)

and

mynum <- 4
factorialcalc(mynum)

When I call this new vector, I would like to see a vector with all three of their outputs (so almost like I made a vector c(120,6,24))

I'm thinking there's a way to add this vector somewhere in my function or while loop, but I'm not sure where. Also, please note that the answer must contain a loop like in my code.


Solution

  • Option 1.

    "Vectorize" your function

    # simply wrap the whole thing in Vectorize()
    Factorialcalc = Vectorize(function(i){
      factorial <- 1
      if(i==0 | i==1){
        factorial <- 1
      } else{
        while(i >= 1){
          factorial <- factorial * i
          i <- i-1
        }
      }
      return (factorial)
    })
    # Now when you supply it a vector, it runs on each element
    > Factorialcalc(c(5, 3, 4))
    [1] 120   6  24
    

    Option 2.

    Use functions that are designed to apply a single function to multiple elements of a supplied vector. Using map_dbl from the purrr package, you can call:

    map_dbl(c(5, 3, 4), factorialcalc)
    

    Which supplies to your function factorialcalc each element in vector and concatenates each result before returning a vector.

    Using base R you can simply use the apply-family functions:

    sapply(c(5, 3, 4), factorialcalc)
    

    and get the same result.

    Example

    > map_dbl(c(5, 3, 4), factorialcalc)
    [1] 120   6  24
    > sapply(c(5, 3, 4), factorialcalc)
    [1] 120   6  24