Search code examples
rscoring

I want to give a score based on the result of the game, but an error occurs


I have a problem in scoring game The game is Russian roulette I want to replicate the game 10 times and give a point to the survivors

game <- replicate(10, shot())
data.frame(table(game))

and I got this game result

              game Freq
1 player1 game end    4
2 player3 game end    2
3 player4 game end    1
4 player6 game end    3

I want to know how I can convert game results into scores like this by giving one point to the survivors

1 player1 point 6
2 player2 point 10
3 player3 point 8
4 player4 point 9
5 player5 point 10
6 player6 point 7

but I don't get any clue about it I desperately need some help

I add my code

shot <- function()
{
  if(sample(c(1,-1),1,prob=c(1/6,5/6)) == T) 
  {
    print("player1 game end") #if p1 get true at 1st round it end
  }
  else if(shot <- sample(c(1,-1),1,prob=c(1/5,4/5)) == T) 
  {
    print("player2 game end") #if p2 get true at 2nd round it end
  }
  else if(shot <- sample(c(1,-1),1,prob=c(1/4,3/4)) == T) 
  {
    print("player3 game end") #if p3 get true at 3rd round it end
  }
  else if(shot <- sample(c(1,-1),1,prob=c(1/3,2/3)) == T) 
  {
    print("player4 game end") #if p4 get true at 4th round it end
  }
  else if(shot <- sample(c(1,-1),1,prob=c(1/2,1/2)) == T) 
  {
    print("player5 game end") #if p5 get true at 5th round it end
  }else if(shot <- sample(c(1,-1),1,prob=c(1,0)) == T) 
  {
    print("player6 game end") #if p6 get true at 5th round it end
  }
}
shot()



My game start with this code How can I combine with scoring code


game
player <- sample(1:6, size = 6, replace = FALSE) 
player

names(player)[player==1] <- "p1"  
names(player)[player==2] <- "p2" 
names(player)[player==3] <- "p3" 
names(player)[player==4] <- "p4" 
names(player)[player==5] <- "p5"



Solution

  • Here's what we can do. First, we create a players data.frame, which we'll use to join up to the games result data.frame. Then we calculate score, which appears to be 10 - Freq:

    # generate games
    set.seed(1) # reproducible
    games <- replicate(10, shot())
    # make players data
    players <- data.frame(player = paste0("player", 1:6))
    # make games data
    games_table <- data.frame(table(games))
    games_table$player <- gsub(" game end", "", games_table$games) # player ID
    # merge data
    players <- merge(players, games_table, all.x = TRUE)
    # create score
    players$score <- 10 - ifelse(is.na(players$Freq), 0, players$Freq)
    
    #    player            games Freq score
    # 1 player1 player1 game end    2     8
    # 2 player2 player2 game end    2     8
    # 3 player3 player3 game end    1     9
    # 4 player4 player4 game end    2     8
    # 5 player5             <NA>   NA    10
    # 6 player6 player6 game end    3     7