Help creating a for loop to demonstrate sampling distribution

Hello all,

I could use some help trying to create a for loop. In this simple demo, I have 4 scores in a vector called y. I want to repeatedly draw samples of size n=2 from y, find the mean of these two drawn scores, and save this mean in the output vector. Rinse and repeat until all possible combinations of scores have been exhausted. This code half works; the problem is it only produces 4 means and I'm not sure how to tell it to keep repeatedly sampling until it has all combinations (e.g. 2/2, 2/4, 2/6, 2/8; 4/2, 4/4, 4/6....etc.).

Any help would be appreciated

y=c(2,4,6,8)

output <- vector("double", length=16) 

for (i in y) {            # 2. sequence
  output[[i]] <- mean(sample(y,size = 2,replace = TRUE))      # 3. body
}
sample(combn(c(2,4,6,8),2,mean),6,replace = FALSE)
#> [1] 4 5 7 6 3 5

Created on 2020-09-20 by the reprex package (v0.3.0.9001)

is guaranteed to produce all combinations of the four objects taken two at a time.

The OP for loop stops when i reaches length(y), which equals 4.

sample is not guaranteed to exhaust the combination, although it likely will with this few, in any finite number of iterations, so this is a stopping problem, also.

What's needed is a sufficiently large number of iterations to have a good chance of exhausting the sample space, but it guaranteed to complete. (Of course if it exhausts the sample space on one run, it does not necessarily exhaust it on the next.)

y <- c(2,4,6,8)
run_cases <- function(x) {
  sample(combn(y,2,mean),6,replace = FALSE) %in% sample(combn(y,2,mean),x,replace = TRUE)
}
run_cases(10)
#> [1] FALSE  TRUE  TRUE  TRUE  TRUE  TRUE
run_cases(10)
#> [1]  TRUE FALSE  TRUE  TRUE  TRUE  TRUE
run_cases(10)
#> [1] TRUE TRUE TRUE TRUE TRUE TRUE

Created on 2020-09-20 by the reprex package (v0.3.0.9001)

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.