Ken
Ken

Reputation: 343

Using the runif function to count occurrences using R

Let's say that the probability that an event occurs is 0.2. I would like to, for example for 50 times, count the amount of times that the event occurs, using the runif function in R.

Is this the correct way to do that? Because it's not really giving the expected outcomes.

X <- 50

amount <- (runif(X)<0.2)

or

amount <- sum(runif(X)<0.2))

Upvotes: 0

Views: 210

Answers (2)

lebatsnok
lebatsnok

Reputation: 6469

Well, strange is something subjective -- random numbers can look strange but still be random. You can check whether your result is actually strange or not:

runs <- replicate(1000, sum(runif(50)<0.2))
mean(runs)  # I got 10.028
median(runs)  # should be exactly 10

Nothing strange here. (I would use rbinom instead of runif here but that shouldn't change much.)

Upvotes: 1

Kitter Catter
Kitter Catter

Reputation: 128

Let's just review this line by line:

The following sets X, the number of trials, to 50.

X <- 50 

Let's look at our choices:

amount <- (runif(X)<0.2)

This will return a vector of T/F values, each the result of a trial with True meaning the event occurs and False meaning the event does not occur.

amount <- sum(runif(X)<0.2))

Is like the previous command but sums over the results. This counts the number of times the event occurs.

Upvotes: 0

Related Questions