我试图模拟两个以上的学生在一个满是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){...}
然后错误开始发生。
答案 0 :(得分:3)
您可能不知道stats包中已存在此功能:
pbirthday(30, classes = 365, coincident = 2)
[1] 0.7063162
还有一个分位数版本:qbirthday
将它包装在一个函数中,但如果您还要在函数内部执行此操作,请不要将参数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
答案 1 :(得分:1)
如果您想使用之前编写的代码并将其简单地包装到函数中,您可以通过让n
和sims
成为用户定义的输入变量来实现,例如@ 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>