[R] Simulating Conditional Distributions

Bernardo Rangel Tura tura at centroin.com.br
Wed Mar 26 04:47:13 CET 2008


On Fri, 2008-03-21 at 22:37 -0700, Sherri Rose wrote:
> Dear R-Help List,
> I'm trying to simulate data from a conditional distribution, and  
> haven't been able to modify my existing code to do so.  I searched  
> the archives, but didn't find any previous post that matched my  
> question.
> 
> n=10000
> pop = data.frame(W1 = rbinom(n, 1, .2),
>    W2 = runif(n, min = 3, max = 8), W3 = rnorm(n, mean=0, sd=2))
> pop = transform(pop,
>    A = rbinom(n, 1, .5))
> pop = transform(pop,
>    Y = rbinom(n, 1, 1/(1+exp(-(1.5*A-.05*W1-2*W2-2*W3+2*A*W1)))))
> 
> In this population the probability of being "diseased" (Y=1) is  
> approx 0.030.  What I want to be able to do is specify a conditional  
> distribution of (A, W1, W2, W3) given that Y=1 and one for (A, W1,  
> W2, W3) given that Y=0.  Then I can sample diseased and non-diseased  
> individuals from these distributions without having to simulate a  
> large base population.  This will be particularly useful when the  
> probability of being "diseased" is even smaller and I want a large  
> number of diseased individuals.
> 
> Any pointers to do this would be extremely helpful!
> Thank you,
> Sherri Rose
> 
> UC Berkeley
> 	[[alternative HTML version deleted]]

If I understand your problem, this script solve your question:

n<-10000
Y<-rbinom(n,1,.3)
A<-ifelse(Y==0,1,rbinom(n, 1, .5))
W1<-ifelse(Y==0,1,rbinom(n, 1, .2))
W2<-ifelse(Y==0,1,runif(n, min = 3, max = 8))
W3<-ifelse(Y==0,1,rnorm(n, mean=0, sd=2))
pop<-data.frame(Y,A,W1,W2,W3)
pop

-- 
Bernardo Rangel Tura, M.D,MPH,Ph.D
National Institute of Cardiology
Brazil



More information about the R-help mailing list