Constantin
Constantin

Reputation: 154

Nested for loop to generate random variables with differing probabilities in R

I am trying to write a for loop that generates random variables from a geometric distribution using different probability values. However, the code I write only uses the last probability in the sequence to generate the random variables, see below.

x <- list()
y <- list()
probs <- seq(0.1, 0.9, 0.1)
for (i in 1:length(probs)) {
  for (j in 1:10000) {
    x[j] <- rgeom(n=1, prob=probs[i])+1
    y[j] <- probs[i]
  }
}

How do I loop along the probabilities to generate 10000 RV for each probability?

Upvotes: 0

Views: 587

Answers (2)

Pedro Faria
Pedro Faria

Reputation: 869

You do not need an nested loop for that. If you just want randomly select an probability to use on the rgeom() function, across 10 thousand iterations, you can do something like below, using the sample() function to choose which prob will be used, and store the results, in a data.frame.

x <- vector(mode = "double", length = 10000)
y <- vector(mode = "double", length = 10000)

probs <- seq(0.1, 0.9, 0.1)

for (i in 1:10000){
 prob <- probs[sample(1:length(probs), size = 1)]
 x[i] <- rgeom(1, prob = prob)
 y[i] <- prob
}

random_values <- data.frame(
  value = x,
  prob_used = y
)

Resulting this:

> head(random_values)
  value prob_used
1     0       0.6
2    23       0.1
3     0       0.6
4     0       0.6
5     2       0.1
6     4       0.3

Upvotes: 1

Dipro Mondal
Dipro Mondal

Reputation: 31

A simple solution could be:

    x <- list()
    y <- list()
    probs <- seq(0.1, 0.9, 0.01)
    j<-1
    for (i in 1:length(probs)) {
      x[[j]] <- rgeom(n=10000, prob=probs[i])+1
      y[[j]] <- rep(probs[i], 10000)
      j<-j+1
    }
    x<- list(unlist(x))
    y<- list(unlist(y))

Upvotes: 1

Related Questions