2017-02-25 8 views
1

私は、2人以上の生徒が同じ人の誕生日を持つ確率をシミュレートしようとしています。現在、私は私のコードは別に私が最初に私の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 

(下記参照)をどのように整理整頓Iだろうこれは変数nが関数内に含まれるようにするためですか?これを次の関数に変換しようとするとすぐに:

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

エラーが発生します。

答えて

1

前に書いたコードを関数に単純にラップすると、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> 
3

あなたは、おそらくこの機能は、すでに統計パッケージに存在することを知りませんでした:

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 
+0

ありがとうございます!偶然のための関数があることを知るには便利です。 – Aesler

+0

置換したランダムサンプルの関数と考えてください。 –

関連する問題