Yorgos
Yorgos

Reputation: 183

Forming groups from a sample in R

I have the following problem:

I have created a sample with 35 numerical observations. From this sample, I want to draw 7 random observations. My code is:

my_sample <- c(1:35) 

group1 <- sample(my_sample, 7)

After that, I want to create a second group (group2) which again will be a vector of 7 numbers drawn from a subset of my_sample, excluding the observations of group1.

Any recommendation how can I achieve this result?

Upvotes: 1

Views: 59

Answers (3)

Yorgos
Yorgos

Reputation: 183

Based on @akrun, I managed to form 5 groups, that each contains 7 observations from my_sample (not so nice solution, though):

  my_sample <- c(1:35) 

    group1 <- sample(my_sample, 7)
    group2 <- sample(setdiff(my_sample, group1), 7)

    # creating an intermediate subset
    group_union <- union(group1, group2)

    group3 <- sample(setdiff(my_sample, group_union), 7)

Upvotes: 1

IceCreamToucan
IceCreamToucan

Reputation: 28675

You could also sample 14 numbers then split it up after. Since the sampling is done without replacement, you're guaranteed to not have any common elements between (non-overlapping) subsets of your sample.

two_samps <- sample(my_sample, 14)
two_samps[c(F, T)]
# [1]  2 17 20 29  1 12 33
two_samps[c(T, F)]
# [1] 22 11 18 34 27 30 28

Upvotes: 1

akrun
akrun

Reputation: 886948

In that case, use setdiff

sample(setdiff(my_sample, group1), 7)

Upvotes: 3

Related Questions