【问题标题】:Birthday Paradox - Function with input variable生日悖论 - 具有输入变量的函数
【发布时间】:2017-02-25 16:58:29
【问题描述】:

我试图模拟在一个满是 n 人的房间里,两个以上的学生生日相同的概率。目前我认为我的代码工作正常,虽然我必须首先运行第一行代码来选择我的 n 值,然后单独运行其余代码(见下文)

n = as.integer(readline(prompt = "Enter the number of students in a room:"))

sims = 10000
x = numeric(sims)

for (i in 1:sims){
s = sample(1:365, n, replace=TRUE)
x[i] = n - length(unique(s))}

samebday = length(which(x>0))/length(x)
samebday

我将如何整理以使变量n 包含在函数中?一旦我尝试将其转换为如下函数:

bday.prob = function(n){...}

然后开始出现错误。

【问题讨论】:

    标签: r function prompt birthday-paradox


    【解决方案1】:

    你可能不知道这个函数已经存在于 stats 包中:

    pbirthday(30, classes = 365, coincident = 2)
    [1] 0.7063162
    

    还有分位数版本:qbirthday

    将其包装在一个函数中,但如果您还打算在函数内部执行 einlut,请不要将参数 n 添加到参数列表中:

     # copied from my console
     bfun <- function(){ n = as.integer(readline(prompt = "Enter the number of students in a room:"))
    + print( pbirthday(n, classes = 365, coincident = 2) )
    + }
    > bfun()
    Enter the number of students in a room:30
    [1] 0.7063162
    

    【讨论】:

    • 谢谢!知道有一个巧合函数很有用。
    • 把它想象成一个随机样本替换函数。
    【解决方案2】:

    如果您想使用您之前编写的代码并将其简单地包装到一个函数中,您可以通过让nsims 成为用户定义的输入变量来做到这一点,就像提到的@42-一样。

    以下是我的解决方案,与您提供的内容略有不同:

    bday.prob = function(n, sims){
      #' @param n is the number of students in a room; user-defined
      #' @param sims is the number of trials; user-defined
    
      x = numeric(sims)
      for (i in 1:sims){
        s = sample(1:365, n, replace=TRUE)
        x[i] = n - length(unique(s))
      }
      samebday = length(which(x > 0))/length(x)
      return(samebday)
    }
    

    使用函数如下:

    bday.prob(n=<User choice>, sims=<User choice>)
    

    bday.prob(n=as.numeric(readline(prompt = "Enter the number of students in a room:")), sims=100)
    ## Enter the number of students in a room: <User choice>
    

    【讨论】:

      猜你喜欢
      • 2022-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多