简体   繁体   中英

How do I get an "if else" loop in r to save values created within the loop and use them in future runs of the loop?

I am trying to run a simple loop that will count my points. You can see the code is very simple. I think there's something I am missing here about saving the values within loops to objects. Most information I find is for more complex loops. Feels like this should be a simple solution that I just don't understand yet.

  test <- function(){

  number <- 2

  loop <- function(){

  entry <- as.numeric(readline(prompt = "Enter Number:"))

    if(entry == number){
      points <- 2 * points
      cat("You have " ,points, " points!", sep ="")
      print("Double points!")
      
    }else{
      print("Lose a point.")
      points <- points - 1
      cat("You have " ,points, " points!", sep ="")
      if(points > (0)){
        loop()
      }else{
        print("You lose!")
      }
     }
    }


   loop()
   } 
   test()

When this runs, user enters 3 and the points become 9 and the loop begins again. If user enters 3 again it should subtract 1 point from 9 to make 8. But the object points value is 9 and will not go less than that.

You should use the current value of points as an input to the loop function. And when you call loop() , if it's not the first call, pass in the current value.

test <- function() {
  number <- 2
  starting_points <- 10
  
  loop <- function(points) {
    entry <- as.numeric(readline(prompt = "Enter Number:"))
    
    if (entry == number) {
      points <- 2 * points
      cat("You have " , points, " points!", sep = "")
      print("Double points!")
      
    } else{
      print("Lose a point.")
      points <- points - 1
      cat("You have " , points, " points!", sep = "")
      if (points > (0)) {
        loop(points)
      } else{
        print("You lose!")
      }
    }
  }
  
  loop(points = starting_points)
}
test()

I'd also suggest not mixing cat() and print() - they have different behavior in some cases. (I'd avoid cat() unless you are, eg, writing to log files or trying to avoid auto-formatting done by print - generally print() or message() is more appropriate.)

### Instead of this:
cat("You have " , points, " points!", sep = "")

## use this:
print(paste0("You have " , points, " points!"))

## or this: 
print(sprintf("You have %s points", points))

您没有为变量点分配任何值。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM