[R] rbinom with computed probability
Berwin A Turlach
berwin at maths.uwa.edu.au
Sat Nov 24 09:59:56 CET 2007
G'day Sigalit,
On Fri, 23 Nov 2007 11:25:30 +0200
"sigalit mangut-leiba" <smangut at gmail.com> wrote:
> Hello,
> I have a loop with probability computed from a logistic model like
> this: for (i in 1:300){
>
> p[i]<-exp(-0.834+0.002*x[i]+0.023*z[i])/(1+exp(-0.834+0.002*x[i]+0.023
> +z[i]))
>
> x and z generated from normal distribution.
> I get 300 different probabilities And I want to generate variables
> from bernulli distribution
> with P for every observation:
>
> T[i]<-rbinom(1,1,p[i])
> But i get missing values for T.
> What I'm doing wrong?
I guess the problem is that in the numerator you have "0.023*z[i]" but
"0.023+z[i]" in the denominator. Thus, some p[i] can be outside of
[0,1] which would produce NAs in T.
But why a for loop? This code is readily vectorised:
p <- exp(-0.834+0.002*x+0.023*z)/(1+exp(-0.834+0.002*x+0.023*z))
HTH.
Cheers,
Berwin
=========================== Full address =============================
Berwin A Turlach Tel.: +65 6515 4416 (secr)
Dept of Statistics and Applied Probability +65 6515 6650 (self)
Faculty of Science FAX : +65 6872 3919
National University of Singapore
6 Science Drive 2, Blk S16, Level 7 e-mail: statba at nus.edu.sg
Singapore 117546 http://www.stat.nus.edu.sg/~statba
More information about the R-help
mailing list