[R] 3 questions regarding matrix copy/shuffle/compares
Esmail
esmail.js at gmail.com
Sun Apr 26 17:36:57 CEST 2009
David,
Good news! It seems that R has deep copy by default. I ran this simplified
test and it seems I can change 'pop' without changing the saved version.
POP_SIZE = 4
LEN = 8
pop=create_pop_2(POP_SIZE, LEN)
cat('printing original pop\n')
print(pop)
keep_pop = pop
pop[1,1] = 99
cat('printing changed pop\n')
print(pop)
cat('printing keep_pop\n')
print(keep_pop)
-----------
> source('mat.R')
[1] 32
printing original pop
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,] 0 1 1 0 1 0 0 1
[2,] 1 0 1 0 0 0 1 1
[3,] 0 1 0 1 1 1 0 1
[4,] 0 0 0 1 0 1 0 0
[5,] 0 0 0 0 0 0 0 0
[6,] 0 0 0 0 0 0 0 0
[7,] 0 0 0 0 0 0 0 0
[8,] 0 0 0 0 0 0 0 0
printing changed pop
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,] 99 1 1 0 1 0 0 1
[2,] 1 0 1 0 0 0 1 1
[3,] 0 1 0 1 1 1 0 1
[4,] 0 0 0 1 0 1 0 0
[5,] 0 0 0 0 0 0 0 0
[6,] 0 0 0 0 0 0 0 0
[7,] 0 0 0 0 0 0 0 0
[8,] 0 0 0 0 0 0 0 0
printing keep_pop
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,] 0 1 1 0 1 0 0 1
[2,] 1 0 1 0 0 0 1 1
[3,] 0 1 0 1 1 1 0 1
[4,] 0 0 0 1 0 1 0 0
[5,] 0 0 0 0 0 0 0 0
[6,] 0 0 0 0 0 0 0 0
[7,] 0 0 0 0 0 0 0 0
[8,] 0 0 0 0 0 0 0 0
Re Shuffle
I tried using sample based on your earlier post, but your example
really helped, thanks! That solves the shuffling issue.
dx <- sample(1:POP_SIZE, POP_SIZE)
cat('shuffled index:')
print(dx)
print(pop[dx,])
cat('shuffled pop')
pop[1:POP_SIZE,] = pop[dx,]
print(pop)
re compare:
> I am unclear why you would not create an original and a copy,
Well .. that I wanted to do from the start (hence my question about
deep copy :-)
> work on the copy, and compare with the original that is also sorted
> by the external index.
That's a great idea, hadn't thought of keeping the index around for
this, I'll give this a try.
Final question, how do I compare these two structures so that I get
one result, true or false? Right now
keep == pop yields all these individual comparisons:
> pop==keep
[,1] [,2] [,3] [,4] [,5]
[1,] FALSE TRUE FALSE TRUE FALSE
[2,] FALSE TRUE FALSE TRUE FALSE
[3,] TRUE TRUE TRUE TRUE TRUE
[4,] TRUE TRUE TRUE TRUE TRUE
[5,] TRUE TRUE TRUE TRUE TRUE
[6,] TRUE TRUE TRUE TRUE TRUE
Thanks for the help, much appreciated.
Esmail
More information about the R-help
mailing list