简体   繁体   中英

How to create a data matrix for my loop in R?

I have a for loop that sample one theta[j] from Beta distribution for j=1, 2, ..., 71, then get 100 yrep[k] from each theta[j]. How to fill these data into a 71 by 100 data matrix?

 theta<-NULL
 yrep<-NULL
 test<-NULL
  k=1
 for(i in 1:100){for(j in 1:71){
   theta[j] <- rbeta(1,10+y[j], 20+n[j]-y[j])
  yrep[k]<-rbinom(1, n[j], theta[j])
    k=k+1}
 }
 datatest=data.frame(y)

where the data

  #Data
  y <- c(0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,
   2,1,5,2,5,3,2,7,7,3,3,2,9,10,4,4,4,4,4,4,4,10,4,4,4,5,11,12,
   5,5,6,5,6,6,6,6,16,15,15,9,4)
  n <- 
   c(20,20,20,20,20,20,20,19,19,19,19,18,18,17,20,20,20,20,19,19,18,18,25,24,
   23,20,20,20,20,20,20,10,49,19,46,27,17,49,47,20,20,13,48,50,20,20,20,20,
   20,20,20,48,19,19,19,22,46,49,20,20,23,19,22,20,20,20,52,46,47,24,14)

You can do this with one-loop :

theta<-NULL
mat <- matrix(nrow = 71, ncol = 100)

for(j in 1:71) {
  theta[j] <- rbeta(1,10+y[j], 20+n[j]-y[j])
  mat[j, ] <- rbinom(100, n[j], theta[j])
}

dim(mat)
#[1]  71 100

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM