R - How to sample pairs from an array without repeating values?

Asked

Viewed 98 times

3

I’m trying to create 100 pairs from a 200 value vector. I built a vector following a normal distribution as follows:

vetor=rnorm(200,mean=30,sd=6)

And now I want to extract 100 pairs of these values, but without repeating any of them. I tried to do it this way:

pares=replicate(100,sample(vetor,2,replace=FALSE))

In that case, replace=FALSE prevented equal pairs from being sampled, but some vector values entered more than one pair, and other values did not enter any pair.

What I want is for all values to be part of some pair and for all pairs to be different.

Someone could help me?

1 answer

5


It’s easier to do that than you think. More exactly, you don’t have to use the replicate. Suffice it to see that sample(vetor) produces a permutation of your argument. (No repetitions.)

set.seed(3604)    # para que os resultados sejam reprodutíveis 
vetor <- rnorm(200, mean = 30, sd = 6)

pares <- matrix(sample(vetor), nrow = 2)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.