Split vector randomly into two sets

user969113 picture user969113 · Sep 4, 2012 · Viewed 8.7k times · Source

I have a vector t with length 100 and want to divide it into 30 and 70 values but the values should be chosen randomly and without replacement. So none of the 30 values are allowed to be in the sub vector of the 70 values and vice versa.

I know the R function sample which I can use to randomly chose values from a vector with and without replacement. However, even when I use replace = FALSE I have to run the sample function twice once with 30 and once with 70 values to chose. That means that some of the 30 values might be in the 70 values and vice versa.

Any ideas?

Answer

seancarmody picture seancarmody · Sep 4, 2012

How about this:

t <- 1:100 # or whatever your original set is
a <- sample(t, 70)
b <- setdiff(t, a)