Section 4.3: Random Variables

Example: Tossing a coin four times

Let the random variable X represent the number of Heads in the ourtcome after tossing a coin four times.

X<-c(0,1,2,3,4)

Let P represent the probabilities of each of the values of X. Note: Make sure to enter these in the order that corresponds to the values in X (e.g. the second value in P should give the probability of the second value in X).

P<-c(.0625, .25, .375, .25, .0625)

We can use the random number generator command named sample to pick a value of X at random. Note that since the different values of X have different probabilities, we must give the name of the variable that has the probabilities.

sample(X, 1, prob=P)
## [1] 3

Let’s repeat this experiment 1000 times and save the results into the a data set called coins.

coins<-do(1000)*sample(X, 1, prob=P)

Now, we can look at the probability distribution on a histogram.

histogram(~result, data=coins)

Let’s make the width of each bar 1 to make the histogram look nicer:

histogram(~result, data=coins, width=1)

Example: Uniform Distribution

Plot a uniform distribution, to find the probability that a randomly selected number from 0 to 1 is between 0.3 and 0.7.

pdist("unif", min=0, max=1, c(0.3, 0.7))

## [1] 0.3 0.7

We can divide the area under the curve into as many pieces as we want:

pdist("unif", min=0, max=1, c(0.1, 0.3, 0.7, 0.9))

## [1] 0.1 0.3 0.7 0.9