Search code examples
rloopsvectorrandomsample

R: producing vector with number of times an element appears in sample


I have a homework problem where I have a sample of 30 men, a random sampling of 10 of them:

men [1] 15 18 14 6 22 17 20 3 16 9

And From them, do 12 random samples and determine how many times each man appears.

The problem statement, verbatim, is "Perform 12 samples of 10 men from a population of size 30 and for each man, record the number samples in which he appears."

I have attempted a loop for the problem that would produce a vector of 10 elements, each one lined up with the appropriate index.

mtimes<-rep(0,12)
> repeat{
+ mtimes[menind]<-sum(sample(pop1,12,replace = TRUE) == men[menind])
+ menind = menind + 1
+ if (menind == 10){
+ break
+ }
+ }

This resulted in a vector:

mtimes [1] 0 0 1 0 0 0 0 0 0 0

It seems the 3rd man should not have appeared only once while no one else appeared in the samples.


Solution

  • You can use replicate and table here

    set.seed(1)
    table(replicate(n = 12, expr = sample(30, size = 10, replace = TRUE)))
    # 1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 
    # 3  2  3  5  2  2  5  5  3  3  6  7  4  5  8  2  1  3  2  9  3  7  2  8  3  3  5  3  3  3
    

    I assume that by "men" you mean 1:30.


    Another option would be to increase the size of the sample to 10*12 as in

    set.seed(1)
    table(sample(30, size = 10*12, replace = TRUE))