Reputation: 351
I've looked through about 7 different answers, plus searched help files, and no luck (haven't used R in a loooong time, so, I'm pretty rusty).
I have a vector that represents a population of n players playing s different survival strategies, and I want to randomly pair up each element with another. Originally I tried the code below, but obviously that can't work, since the resulting object has n elements, whereas my resulting object should have n/2.
popsize = 10
nstrats = 3
Population <- sample(1:nstrats, popsize, T)
Opponents <- sample(Population)
Pairings <- cbind(Population, Opponents)
I'm trying to do this without a loop, though I'll gladly take any suggestions (especially if using a loop is the only way to do it!)
Many thanks in advance!
Upvotes: 2
Views: 3729
Reputation: 10203
This will give you a list of pairings from the Population (it just splits Population
into pairs):
split(Population,rep(1:(popsize/2),each=2))
If you want to randomly pair elements of Population
just shuffle it before you create the pairings:
split(sample(Population),rep(1:(popsize/2),each=2))
Upvotes: 3