Hi, I need to create a function which generates a Binomial random number without using the rbinom function. Do I need to use the choose function or am I better just using a sample? Thanks. -- View this message in context: http://r.789695.n4.nabble.com/Binomial-tp3516778p3516778.html Sent from the R help mailing list archive at Nabble.com.
Am 12.05.2011 10:46, schrieb blutack:> Hi, I need to create a function which generates a Binomial random number > without using the rbinom function. Do I need to use the choose function or > am I better just using a sample? > Thanks.I think I remember other software who generates binomial data with e.g. pi=0.7 by pi <- 0.7 x <- runif(100)>pi summary(x) -- Alex
On 12-May-11 09:02:45, Alexander Engelhardt wrote:> Am 12.05.2011 10:46, schrieb blutack: >> Hi, I need to create a function which generates a Binomial random >> number >> without using the rbinom function. Do I need to use the choose >> function or >> am I better just using a sample? >> Thanks. > > I think I remember other software who generates binomial data > with e.g. pi=0.7 by > > pi <- 0.7 > x <- runif(100)>pi > summary(x) > > -- AlexThat needs to be the other way round (and perhaps also convert it to 0/1): x <- 1*(runif(100) < pi) since Prob(runif > pi) = (1 - pi). Comparison: pi <- 0.7 x <- runif(100)>pi x[1:10] # [1] FALSE TRUE TRUE FALSE FALSE TRUE TRUE TRUE FALSE FALSE sum(x)/100 # [1] 0.36 x <- 1*(runif(100) < pi) x[1:10] # [1] 0 0 1 1 1 1 1 0 1 0 sum(x)/100 # [1] 0.62 Ted -------------------------------------------------------------------- E-Mail: (Ted Harding) <ted.harding at wlandres.net> Fax-to-email: +44 (0)870 094 0861 Date: 12-May-11 Time: 10:21:26 ------------------------------ XFMail ------------------------------
On May 12, 2011, at 5:02 AM, Alexander Engelhardt wrote:> Am 12.05.2011 10:46, schrieb blutack: >> Hi, I need to create a function which generates a Binomial random >> number >> without using the rbinom function. Do I need to use the choose >> function or >> am I better just using a sample? >> Thanks. > > I think I remember other software who generates binomial data with > e.g. pi=0.7 by > > pi <- 0.7I hope Allan knows this and is just being humorous here, but for the less experienced in the audience ... Choosing a different threshold variable name might be less error prone. `pi` is one of few built-in constants in R and there may be code that depends on that fact. > pi [1] 3.141593 > pi <- 0.7 > pi [1] 0.7 > rm(pi) > pi [1] 3.141593> x <- runif(100)>pi > summary(x)Another method would be: x <- sample(c(0,1) , 100, replace=TRUE, prob=c(0.7, 0.3) ) -- David Winsemius, MD West Hartford, CT