首页 > 解决方案 > rolldie 的 prob 函数,但我不知道如何写得很清楚,请参阅问题 b

问题描述

前提条件:已经安装了“prob”包和它需要的严重包

a) 考虑掷三个骰子的实验。使用 R,展示您将如何使用用户定义的函数来定义一个随机变量,该变量是四舍五入到最接近整数的三个滚动的平均值。

> rollthree <- rolldie(3, makespace = TRUE)
> rollthree$mean = as.integer((rollthree$X1 + rollthree$X2 + rollthree$X3)/3)
> rollthree
    X1 X2 X3      probs mean
1    1  1  1 0.00462963    1
2    2  1  1 0.00462963    1
... ...

b) 使用上述结果,随机变量等于 3 的概率是多少?随机变量取值最多为 3 的概率是多少?随机变量取值至少为 3 的概率是多少?使用代码示例中所示的 Prob 函数。

> equal3 <- subset(rollthree$mean, rank == 3)
Error in rank == 3 : 
  comparison (1) is possible only for atomic and list types```

标签: r

解决方案


我相信这里的问题是子集不能在等级上运行,解决这个问题的一个解决方案是在equal3 <- subset(rollthree, mean == 3)我们的平均值为 3 的情况下存储所有行。然后我们可以对概率求和或将概率相乘单卷按数组的长度。

使用您的代码作为基础,我生成了以下代码。

library(prob)

# Part a

rollthree <- rolldie(3, makespace = T)
rollthree$mean = as.integer((rollthree$X1 + rollthree$X2 + rollthree$X3)/ 3)

# Part b

print("Probability mean is 3:")
# Note here we sum the probablities from the events we want to occur
# Additionally we have done this all in one line by taking only the mean column from the subset
sum(subset(rollthree, mean == 3)$prob)

print("Probability mean is less than or equal to 3:")
sum(subset(rollthree, mean <= 3)$prob)

print("Probability mean is greater than or equal to 3:")
sum(subset(rollthree, mean >= 3)$prob)

#> [1] "Probability mean is 3:"
#> [1] 0.3657407

#> [1] "Probability mean is less than or equal to 3:"
#> [1] 0.625

#> [1] "Probability mean is greater than or equal to 3:"
#> [1] 0.7407407

reprex 包创建于 2021-06-08 (v2.0.0 )

a) 的另一种方法如下所示:

library(prob)

# part a

#function to roll and calculate the means for some number of dice
roll_x_mean_int <- function(x) {
  # Check the input value is an integer
  if(typeof(x) != "integer"){
    stop("Input value is not an integer")
  }
  # Check the input value is positive
  if(x < 1){
    stop("Input integer is not positive")
  }
  # Roll the die
  vals <- rolldie(x, makespace = T)
  # Calculate the sum of each row (excluding the value of the probability)
  vals$mean <- as.integer(rowSums(vals[1:x]/x))
  return(vals)
}

# Call the fucntion with 3 dice (note the L makes the value an integer)
rollthree <- roll_x_mean_int(3L)

# part b

# Called this section as one block
{
  print("Probability mean is 3:")
  print(sum(subset(rollthree, mean == 3)$prob))

  print("Probability mean is less than or equal to 3:")
  print(sum(subset(rollthree, mean <= 3)$prob))

  print("Probability mean is greater than or equal to 3:")
  print(sum(subset(rollthree, mean >= 3)$prob))
}
#> [1] "Probability mean is 3:"
#> [1] 0.3657407

#> [1] "Probability mean is less than or equal to 3:"
#> [1] 0.625

#> [1] "Probability mean is greater than or equal to 3:"
#> [1] 0.7407407

reprex 包创建于 2021-06-08 (v2.0.0 )


推荐阅读