mardi 1 décembre 2015

How to make a 0 stay as a 0 in a matrix

I use the following code to generate a matrix

randomdiv <- function(nchrom, ndivs, size) {sz <- matrix(nrow = nchrom, ncol = ndivs) 

for (j in 1:nchrom) {
     n <- size
for (i in 1:ndivs)
    {
     old_subs <- rbinom (1, n, 0.5)  
     num_chrom <- rep(1/nchrom, nchrom)    
     new_subs <- rmultinom(1, size*nchrom/2, prob = c(num_chrom))
     m <- old_subs + new_subs        
     sz[j,i] <- m[1,1]
     n <- m
    }
   }
  return (sz)
 }

>randomdiv(3, 3, 10)
      [,1] [,2] [,3]
  [1,]   11   13   12
  [2,]    6    8    5
  [3,]   12   11    9

The only adjustment I need to make is that when a 0 is generated in the column by the rbinom function, I need that occurence to stay as a 0 for the remainder of the matrix, but anything >0 needs to go through the rest of the loop and have new_subs added to it.

I have tried;

randomdiv <- function(nchrom, ndivs, size, ncell) {sz <- matrix(nrow = nchrom, ncol = ndivs) 

for (j in 1:nchrom) {
     n <- size
for (i in 1:ndivs)
     {
      old_subs <- rbinom (1, n, 0.5)  
      num_chrom <- rep(1/nchrom, nchrom)    
      new_subs <- rmultinom(1, size*nchrom/2, prob = c(num_chrom))
      m <- ifelse(old_subs>0, old_subs + new_subs, old_subs+0)         
      sz[j,i] <- m[1,1]
      n <- m
     }
    }
   return (replicate(ncell, sz, simplify = FALSE))
  }
> randomdiv(3, 3, 10, 5)
#Error in m[1, 1] : incorrect number of dimensions

I've tried a few different tactics with the ifelse function, but I think it only treats the columns as a whole, so if there is a 0 at all, nothing happens for the whole column, whereas I need each value in the columns to be treated individually.

Aucun commentaire:

Enregistrer un commentaire