生日悖论 - 带输入变量的函数

Birthday Paradox - Function with input variable

我正在尝试模拟在一个满是 n 个人的房间里有两个以上学生生日相同的概率。目前我认为我的代码工作正常,虽然我最初只需要 运行 第一行代码到 select 我的 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){...}

然后开始出现错误。

您可能不知道这个函数已经存在于统计包中:

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

如果你想使用你之前编写的代码并将其简单地包装到一个函数中,你可以通过让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>