Nasi Jofce
Nasi Jofce

Reputation: 11

Generate a random vector multiple times until a condition is complete

I have a vector x=(1,2,3,4,...20) and I want to generate vectors with 5 elements from this vector(elements can be repeated), until there are shown all the elements of the first vector at least once. And then I have to represent the data with a histogram. Any idea how can I do this? Thanks in advance

Upvotes: 0

Views: 255

Answers (3)

Gopala
Gopala

Reputation: 10473

You can get a sample of five elements doing this with replacement (you can set that to false if you don't want replacement sampling):

x <- seq(1:20)
shown <- rep(0, 20)
while (!all(shown > 0)) {
  s <- sample(x, 5, replace = TRUE)
  shown[s] <- shown[s] + 1
}
hist(shown)

Upvotes: 0

Heroka
Heroka

Reputation: 13139

A while loop seems a good way to go here. This solution uses a matrix to capture your samples. Each sample is one row. This makes it easier to do other operations per sample, if you so desire.

set.seed(123)  

base_v <- 1:20

#empty matrix to put samples in
mydat <- matrix(nrow=0,ncol=5)

while(!all(base_v %in% mydat)){
  mydat <- rbind(mydat, sample(base_v,size=5,replace=T))
}

#then making the histogram is trivial
hist(mydat)

Upvotes: 3

Mirek Długosz
Mirek Długosz

Reputation: 4275

I think this is what you want:

x <- 1:20
s <- integer(0)
while (! all(x %in% s)) {
  s <- c(s, sample(x, 5, TRUE))
}

Vector s will contain all values drawn from x. I trust you will be able to make histogram from it on your own.

Line-by-line explanation:

  • x <- 1:20 - initialize vector x with numbers 1..20
  • s <- integer(0) - initialize empty vector s that will store all the results
  • x %in% s - for every element in x, check if it appears anywhere in s and return boolean (logical) value
  • all(…) - return TRUE if all elements in argument vector are TRUE; return FALSE otherwise (if at least one is not TRUE)
  • ! - logical negation
  • while - loop that will repeat body as long as condition is evaluated to TRUE
  • to sum up: as long as at least one element from x is not in s, execute code in loop body
  • sample(x, 5, TRUE) - draw five elements from vector x, allow repetitions
  • s <- c(s, sample(x, 5, TRUE)) - concatenate drawn values to vector s and assign this new vector back to s

Upvotes: 1

Related Questions