2

I want to simulate one column of y and n*N x matrix with one column as y and N columns as x.

 y x1 x2 x3 ... xN
 1  1  0  1 ... 1
 0  1  1  0 ... 1
 .  .  .  . ... .
 .  .  .  . ... .
 0  1  0  1 ... 1

At the same time, I need to simulate a data matrix beta, which is the coefficients between y and x. so the matrix will look like

 y  x1        x2      x3   ...   xN
 1  beta11  beta12  beta13 ... beta1N
 0  beta21  beta22  beta23 ... beta2N
 .    .        .      .    ...    .
 .    .        .      .    ...    .
 0  betan1  betan2  betan3 ... betanN

There is some relationship between x and y, but that is not the point of my question. The simulation scheme is:

n=100

N= 1000

p=0.5

  1. y<- rbinom(n, 1, p) #I first generate the column with 100 rows for y
  2. beta<- rnorm(n,0,1) #beta is the coefficient in the model with y and x
  3. p1<-runif(n,0,1)
  4. p2<-exp(beta)*p1
  5. x<-rbinom(n,1,p2)#x is have relationship with beta and p1, so x is sampled in this way.

The simulation scheme is just for generating one column with n observations of y and one column with n observations of x, so I need a for loop to create the matrix for beta and x. My codes are:

n =100
N = 1000
p<- 0.52
y<- rbinom(n,1,p) #generate y

for (i in 1:N){

  beta[i] <-rnorm(n, 0, 1 )

  p1[i] <- runif(n, 0, 1)
  p2[i] <- exp(beta)*p1
  x[i]<- rbinom(n, 1, p2)
  }

The error occurs:

Error in beta[i] <- rnorm(n, 0, 1) : 
  object of type 'closure' is not subsettable

I think my codes are logical, could anyone tell me how to fix them?

user5802211
  • 197
  • 1
  • 9
  • I think you cannot directly use `beta`, `p1` etc. You first need to initialise them. – Ronak Shah May 31 '17 at 09:15
  • @RonakShah If I pre-set `beta, p1, p2 and x <- numeric()`, the warning message `number of items to replace is not a multiple of replacement length` will occur and all variables are filled with `NAs`. I search this question online but still not know how to do. – user5802211 May 31 '17 at 09:21

0 Answers0