R中的And / Or语句问题

时间:2016-01-28 20:13:14

标签: r

我正在创建一个代码来模拟一个简单的老虎机。在我的函数'slot_machine'中,我继续遇到我的第二个if语句

的问题
else if (drum1==2|3|4|5 & drum2==2|3|4|5 & drum3==2|3|4|5){    
payout <- 114}

即使条件不满足,它也会使支付价值达到114美元。我是编码的新相对论,所以这可能是一个愚蠢的错误。如果您有任何建议或想法,我将非常感谢。

谢谢。

cat("\014")
# d)
slot_machine <- function(payout){
  drum1 <- 1
  drum2 <- 1
  drum3 <- 7
  if (drum1==drum2 & drum2==drum3){
    if (drum1==1){
      payout <- 3000
    }
    else if (drum1==2|3|4|5){
      payout <- 114
    }
    else{
      payout <- 0
    }
  }

  else if (drum1==2|3|4|5 & drum2==2|3|4|5 & drum3==2|3|4|5){
    payout <- 114
  }

  else{
    payout <- 0
  }
}

number_of_plays <- 5
total_gain = number_of_plays*2
array = rep(NA,number_of_plays)
total_loss <- 0
for (i in 1:number_of_plays){
  array[i] <- slot_machine(payout)
  total_loss <- total_loss + array[i]
}
profit = total_gain - total_loss

1 个答案:

答案 0 :(得分:2)

除了上面的评论之外,还可以对您的模拟进行其他改进:

slot_machine <- function() {
        #only one 'drums' variable with 3 values from 1 to 5
        drums <- sample(1:5,3, replace=T)
        #use length of unique drums. It will be equal to 1 when drums are the same
        if(length(unique(drums)) == 1) {
                #'1' is the biggest payoff '3000' for wins, '114' for other matches
                #We use 'return()' bc it terminates the function.
                if(drums[1] == 1) return(3000) else return(114)
        } else {
                #for losses
                return(0)
        }    
}

#simulate a game of slots. User chooses how many times to play
#and the cost per play
play_slots <- function(plays, cost_per_play) {

        #gain starts at zero
        total_gain <- 0

        #simulate games
        for(i in 1:plays) {
             total_gain <- total_gain + slot_machine()   
        }

        #calculate profits
        profit <- total_gain - cost_per_play*plays
        return(profit)
}

#A game example. 100 plays, 1 unit of cost per play
set.seed(128)
play_slots(100, 1)
[1] 356