2017-05-29 30 views
2

我想從以下模型生成Xi。我知道如何從binomial distribution生成數據,我可以做的是如下,但我怎樣才能生成數據在同一時間滿足條件,Y = 1Y =-1R:如何生成這個條件二項式隨機變量?

set.seed(100) 
n1<-50 
n2<-50 
p1<- 0.4 
p2<- 0.3 

y <- c(rep(1,50),rep(-1,50)) 
xi1<- c(rbinom(n1,1,p1), rbinom(n2,1,p2)) 

enter image description here

+1

@李哲源ZheyuanLi謝謝,但你能補充一些解釋嗎?我看不出在哪裏表示「給定Y = 1或-1」。 – user5802211

回答

2

因爲rbinom()被矢量,我們可以做

n <- ifelse(y == 1, n1, n2) 
p <- ifelse(y == 1, p1, p2) 
rbinom(n, 1, p) 

你最好閱讀?rbinom密切。