[R] 3 questions regarding matrix copy/shuffle/compares

Esmail esmail.js at gmail.com
Sun Apr 26 06:28:22 CEST 2009


Hello all,

I have the following function call to create a matrix of POP_SIZE rows
and fill it with bit strings of size LEN:

    pop=create_pop_2(POP_SIZE, LEN)

I have 3 questions:

(1) If I did

     keep_pop[1:POP_SIZE] == pop[1:POP_SIZE]

     to keep a copy of the original data structure before manipulating
     'pop' potentially, would this make a deep copy or just shallow? Ie
     if I change something in 'pop' would it be reflected in 'keep_pop'
     too? (I don't think so, but just wanted to check). I would like
     two independent copies.

(2) If I wanted to change the order of *rows* in my matrix 'pop', is there
     an easy way to shuffle these? I don't want to change anything in the
     columns, just the complete rowsn (E.g., in Python I could just say
     something like suffle(pop) assuming pop is a list of list) - is there
     an equivalent for R?

(3) I would like to compare the contents of 'keep_pop' with 'pop'. Though
     the order of rows may be different it should not matter as long as
     the same rows are present. Again, in Python this would be simply

     if sorted(keep_pop) == sorted(pop):
        print 'they are equal'
     else
        print 'they are not equal'

     Is there an equivalent R code segment?

Thanks,

Esmail

--------------- the code called above -------------


####################################################
# create a binary vector of size "len"
#
create_bin_Chromosome <- function(len)
{
   sample(0:1, len, replace=T)
}



############## create_population ###################
# create population of chromosomes of length len
# the matrix contains twice as much space as popsize
#
create_pop_2 <- function(popsize, len)
{
   datasize=len*popsize
   print(datasize)
   npop <- matrix(0, popsize*2, len, byrow=T)

   for(i in 1:popsize)
     npop[i,] = create_bin_Chromosome(len)

   npop
}




More information about the R-help mailing list