[R] rearrange set of items randomly

(Ted Harding) ted.harding at wlandres.net
Tue Nov 8 09:59:38 CET 2011


On 08-Nov-11 07:46:15, flokke wrote:
> Sorry, but I dont think that I get what you mean (I am a
> quite new user though)
> I hae a data file of a sample, so I cannot use random numbers,
> the only thing I want to do is to randomly reassign the order
> of the items.

The simplest method of randomly re-ordering is to use
sample() to re-arrange (1:N) randomly, where N is the
number of items in the data. Then use the result to
access the items. Example:

  D <- data.frame(X1=c(1.1,2.1,3.1,4.1),
                  X2=c(1.2,2.2,3.2,4.2))
  N <- nrow(D)
  ix <- sample((1:N))
  D
  #    X1  X2
  # 1 1.1 1.2
  # 2 2.1 2.2
  # 3 3.1 3.2
  # 4 4.1 4.2
  N
  # [1] 4
  ix
  # [1] 3 2 4 1
  D[ix,]
  #    X1  X2
  # 3 3.1 3.2
  # 2 2.1 2.2
  # 4 4.1 4.2
  # 1 1.1 1.2

Note that the defaults for sample() are (see ?sample):

  For 'sample' the default for 'size' is the number
  of items inferred from the first argument, so that
  'sample(x)' generates a random permutation of the
  elements of 'x' (or '1:x').

and the default for the 'replace' option is "FALSE",
so sample((1:N)) samples N from (1:N) without replacement,
i.e. a random permutation.

Ted.

--------------------------------------------------------------------
E-Mail: (Ted Harding) <ted.harding at wlandres.net>
Fax-to-email: +44 (0)870 094 0861
Date: 08-Nov-11                                       Time: 08:59:35
------------------------------ XFMail ------------------------------



More information about the R-help mailing list