You can choose the parameter of the distribution to be anything you like.
Here are the function names: rbernoulli, rbinom, rgeom, rpois
. Think of the “r” as “generate Random number”.
Reading the help files is hard at first, but it is an essential skill. Have a look at their help files. What are the 8 headings?
?rbinom
?rgeom
?rpois
# generate a single Bernoulli random variable:
library(purrr)
rbernoulli(n = 1, p=.5)
## [1] FALSE
# generate a single Binomial random variable:
rbinom(n = 1, size = 10, prob = .3)
## [1] 3
# generate a single Geometric random variable:
# generate a single Poisson random variable:
# generate 10 Bernoulli random variables:
rbernoulli(n = 10, p=.5)
## [1] FALSE FALSE FALSE FALSE TRUE TRUE TRUE FALSE TRUE FALSE
# generate 10 Binomial random variables:
# generate 10 Geometric random variables:
# generate 10 Poisson random variables:
One way to think about random variables is through their “distribution”. To see what the distribution of a random variable looks like, generate 10,000 copies of the random variables above and put them in a histogram:
# Bernoulli:
hist(rbinom(n = 10000,size = 1,prob = .3))
# or
library(magrittr)
##
## Attaching package: 'magrittr'
## The following object is masked from 'package:purrr':
##
## set_names
rbinom(10000,1,.3) %>% hist
# Binomial:
# Geometric:
# Poisson:
Repeat the last step, but change the value of the parameter that you put in.
# Bernoulli:
hist(rbinom(10000,1,.3))
# or
library(magrittr)
rbinom(10000,1,.6) %>% hist
# Binomial:
# Geometric:
# Poisson:
Answer in words:
Before next week’s homework, write down a sequence of heads and tails of length 200 in the code chunk below. Make the sequence as random as possible without actually flipping a coin or generating randomv variables on the computer. Just try to make them random by writing them down.
# Turn on caps lock and let it rip:
myFlips = "HTHHTHTHTTHH..."
nchar(myFlips) #make sure it length 200
## [1] 15