开发者

How do I split a vector into two columns to create ordered pairs for random assignment

开发者 https://www.devze.com 2023-01-06 02:38 出处:网络
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:

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 fo开发者_如何学Cllowing 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


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()


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.


alternately, if you want a data frame:

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


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

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

精彩评论

暂无评论...
验证码 换一张
取 消