Home > Net >  How do I calculate an average like this in r
How do I calculate an average like this in r

Time:11-28

Probably a stupid question but I have no idea how to do this.

Consider the following game, in which a balanced die with six sides numbered from 1 to 6 is rolled. If a 4 or 1 is rolled, you lose 50 euros. If you roll 2 or 3, nothing happens. If you roll 5, you win 50 euros. If you roll 6, you win 16×50 euros.

We would like to know how much money you can expect to win per game on average. Setting the seed to 990, simulate 5649 repetitions of the game.

Calculate the average of the winnings in these repetitions, as an estimate of the expected value of the winning in the game. Indicate this value circled to 2 decimal places.

CodePudding user response:

Here is a base R way with a logical index on the die side.

set.seed(990)

rolls <- sample(6, 5649, TRUE)

win <- integer(5649)
win[rolls %in% c(1, 4)] <- -50
win[rolls == 5] <- 50
win[rolls == 6] <- 16*50
mean(win)
#> [1] 121.4728

Created on 2022-11-27 with reprex v2.0.2


A simpler way. Create a vector of prizes and index it with the rolls values.

prizes <- c(-50, 0, 0, -50, 50, 16*50)

win <- prizes[rolls]
mean(win)
#> [1] 121.4728

Created on 2022-11-27 with reprex v2.0.2


To output the result with 2 decimal places, just

round(mean(win), 2)
#> 121.47

CodePudding user response:

#Simulation of the dice roll
set.seed(990);dice_roll <- sample(1:6,5649,replace = TRUE)

library(dplyr)

df <- tibble(dice_roll = dice_roll)

df %>% 
  mutate(
    #Setting each dice roll to their respective result
    result = case_when(
      dice_roll == 6 ~ (16*50),
      dice_roll == 5 ~ 50,
      (dice_roll == 2 | dice_roll == 3) ~ 0,
      (dice_roll == 1 | dice_roll == 4) ~ -50,
    )
  ) %>% 
  # The global average
  summarise(average = round(mean(result),2)) %>% 
  pull(average)

[1] 121.47

CodePudding user response:

Could just get the analytical solution: P(X=-50) = 1/3, P(X=0) = 1/3, P(X=50) = 1/6, P(X=16*50) = 1/6.

E[X] = -50/3 0/3 50/6 16*50/6 = 125.

-50/3   0/3   50/6   16*50/6
[1] 125
  • Related