dimanche 29 novembre 2020

How to add Results into a Vector within a Loop 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.

The answer I would be looking for would have an empty vector say answers <- c(), and every time I were to run the function factorialcalc, during the function, I would add the return results from factorial into this new answers vector.

I've tried putting in something like this-

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

This doesn't seem to work, but I think the idea is there.

Thanks in advance for any help.

Aucun commentaire:

Enregistrer un commentaire