[R] substituting elements in vector according to sample(unique(vector))

Arthur Wuster awuster at mrc-lmb.cam.ac.uk
Tue Aug 28 16:12:31 CEST 2007


Assuming I have a vector, such as

v <- c(1,2,1,2,3,3,1)

This vector has three unique elements: 1, 2, and 3.

> unique(v)
[1] 1 2 3

If I shuffle this vector of unique elements, I get something like this:

> sample(unique(v))
[1] 3 2 1

In the vector v I started with, I would now like to replace each element in
unique(v) with the corresponding element (i.e. the element with the same
index) in sample(unique(v)).

In this case, the result should be something like c(3,2,3,2,1,1,3).

In particular, I would like to do this without a slow for loop.
I have tried things like sub(), but they don't seem to be appropriate.
Can anyone provide an elegant solution?

Thank you,

Arthur Wuster
Theoretical and Computational Biology
MRC Laboratory of Molecular Biology
Cambridge, UK

More information about the R-help mailing list