I am trying to make my own function in order to generate nn
random variables from a hypergeometric distribution. I know with rhyper(nn,m,n,k)
, which is an R function, I can directly do it. However, I want to make my own function named rHypG(nn,m,n,k)
. I have made the following function:
rHYPG<-function(nn,m,n,k){
for (i in 1:nn){
x<-seq(nn)
for (j in 1:k){
c<-sample(0:1,1,replace=TRUE,prob=c(m/(m+n),n/(m+n)))
if (c==0){
m<-m-1
x[i]<-x[i]+1
} else if (c==1){
n<-n-1
}
}
}
return(x)
}
When I want to test my function (rHYPG
) for any example like rHYPG(10,7,5,3)
, I see below error at output:
Error in sample.int(length(x), size, replace, prob) :
NA in probability vector
Could you please help me to correct my code in order to resolve its error and generate correctly nn
random variables from a hypergeometric distribution with parameters nn
, m
, n
and k
?
[[Hint: Explanations regarding hypergeometric distribution:
nn
: number of observations. m
: the number of white balls in the urn. n
: the number of black balls in the urn. k
: the number of balls drawn from the urn, hence must be in 0,1,…, m+n.]]
Aucun commentaire:
Enregistrer un commentaire