简体   繁体   English

我如何在 r 中计算这样的平均值

[英]How do I calculate an average like this in r

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.考虑下面的游戏,其中掷出一个平衡的骰子,它有六个面,编号从 1 到 6。 If a 4 or 1 is rolled, you lose 50 euros.如果掷出 4 或 1,您将损失 50 欧元。 If you roll 2 or 3, nothing happens.如果掷出 2 或 3,则什么也不会发生。 If you roll 5, you win 50 euros.如果掷出 5,您将赢得 50 欧元。 If you roll 6, you win 16×50 euros.如果掷出 6,您将赢得 16×50 欧元。

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.将种子设置为 990,模拟游戏重复 5649 次。

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.将此值圈出到小数点后 2 位。

Here is a base R way with a logical index on the die side.这是一个基本的 R 方式,在芯片端有一个逻辑索引。

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创建于 2022-11-27,使用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创建于 2022-11-27,使用reprex v2.0.2


To output the result with 2 decimal places, just到 output 小数点后两位的结果,正好

round(mean(win), 2)
#> 121.47
#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

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.可以直接得到解析解: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. E[X] = -50/3 + 0/3 + 50/6 + 16*50/6 = 125。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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