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] 1

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)