views:

88

answers:

4

I am trying to generate random pairs from 34 subjects for an experiment. Subjects will be assigned ID #'s 1-34. To generate the random ordered numbers (1-34) I used the following code:

  ### Getting a vector of random ordered numbers 1-34###
  pairs<-sample(1:34,34,replace=F)
  pairs
  [1] 16 22  8 13  4 25 18 12 17  5  6 31 29 27 30 23  2 14  9 24 34 21 11  
    3  1 28 33 20 32 26 19 10 15  7

What I would like to do is to take this random ordering of numbers and split every other element of the vector into a column so that I get the following ordered pairs:

   partner1     partner2
    16           22
     8           13
     .            .
     .            .
    15            7

Thoughts or ideas on how to go from the vector to the ordered pairs? Any help or insight would be much appreciated.

-Thomas

+7  A: 

That could be as easy as

 newpairs <- matrix(pairs, ncol=2, byrow=TRUE)

and each row then gives you the pair.

Edit Correct to use matrix()

Dirk Eddelbuettel
it worked using `matrix` instead of `as.matrix` for me
gd047
Yep same for me matrix worked as well. Thanks Dirk and gd047!
Thomas
A: 

Split your vector into matrix and iterate over rows and columns of result. Matrix is presented like 2 dimensional array. So you need to set in this matrix to the first element in row element at the odd position in vector and to the second element in row - even position in vector. var vector = new byte[34]; //fill it

        var matrix = new byte[2,17]; //the code below will fill this matrix, then you need only to print it
        for (var i=0; i < vector.Length; i++)
        {
            var indexPosition = i + 1;
            if (indexPosition % 2 != 0) //odd number
            {
                matrix[0, i/2] = vector[i];
            }
            else //even number
            {
                matrix[1, i / 2] = vector[i];
            }
        }

Code above not tested, but algorythm and idea is clear.

Eugene Cheverda
This question was about R.
Shane
A: 

alternately, if you want a data frame:

df = data.frame(partner1=pairs[1:(length(pairs)/2)],
                partner2=pairs[((length(pairs)/2)+1):length(pairs)])
chrisamiller
A: 

You can also condense Dirk's code above into one line

pairs <- matrix(sample(1:34,34,replace=F), ncol=2)
patrick95350