user10942536
user10942536

Reputation:

Trying to create a dice game in R but function not running

I have a code to make a game where a person rolls the die 4 times and if a roll lands on 6, they win. However, I'm running the code but it doesn't produce an output.

game<-function (n=4){
  count=0
  ceiling(6*runif(1))
  for(i in 1:n){
    if(ceiling(6*runif(1))==6){
      count=1
    }
    else(
      count=0
    )
 if(count=1){
   print("Win")}
  else{
    print("Lose")
  }
  }
}


Upvotes: 0

Views: 204

Answers (2)

aljabadi
aljabadi

Reputation: 543

You can in fact do it much simpler using ifelse to vectorise the if statement. Also, you can avoid intermediate variables (e.g. count):

game<-function (n=4){
  ifelse(6 %in% sample(6, n, replace = TRUE), "Win", "Lose")
}

Upvotes: 3

www
www

Reputation: 39154

I would suggest using any to see if any roll equals to 6, then use return to report the value.

game <- function(n = 4){
  if (any(ceiling(6 * runif(n)) == 6L)){
    return("Win")
  } else {
    return("Lose")
  }
}

Upvotes: 2

Related Questions