Random numbers are critical to many analyses, and consequently R has a wide variety of functions for sampling from different distributions.

A `sample`

function is important workhorse function for generating random values, and its behavior has a few quirks, so itâ€™s worth getting to know it more thoroughly. If you just pass it a number, *n*, it will return a permutation of the natural numbers from *1* to *n*

sample(7) [1] 1 2 5 7 4 6 3

If you give it a second value, it will return that many random numbers between *1* and *n*

sample(7, 5) [1] 7 2 3 1 5

Notice that all those random numbers are different. By default, `sample`

samples without replacement. That is, each value can only appear once. To allow sampling with replacement, pass `replace = TRUE`

sample(7, 10, replace = TRUE) [1] 4 6 1 7 5 3 6 7 4 2

Also, you can select *n* items from a vector

#sample(vec, n) sample(world.series$year, 10) [1] 1906 1963 1966 1928 1905 1924 1961 1959 1927 1934

The following example generates a random sequence of 10 simulated flips of a coin

sample(c("H","T"), 10, replace=TRUE) [1] "H" "H" "H" "T" "T" "H" "T" "H" "H" "T"

By default, sample will choose equally among the set elements and so the probability of selecting either *H* or *T* is 0.5. With a Bernoulli trial, the probability *p* of success is not necessarily 0.5. You can bias the sample by using the `prob`

argument of `sample`

. This argument is a vector of probabilities, one for each set element.

Suppose we want to generate 10 Bernoulli trials with a probability of success *p = 0.8*. We set the probability of *H* to be 0.2 and the probability of *T* to 0.8

sample(c("H","T"), 10, replace=TRUE, prob=c(0.2,0.8)) [1] "T" "T" "T" "T" "T" "H" "H" "T" "H" "T"

What cannot be cured must be endured.
*-*

- Android
- AngularJS
- Databases
- Development
- Django
- iOS
- Java
- JavaScript
- LaTex
- Linux
- Meteor JS
- Python
- Science

- August 2020
- July 2020
- May 2020
- April 2020
- March 2020
- February 2020
- January 2020
- December 2019
- November 2019
- October 2019
- September 2019
- August 2019
- July 2019
- February 2019
- January 2019
- December 2018
- November 2018
- August 2018
- July 2018
- June 2018
- May 2018
- April 2018
- March 2018
- February 2018
- January 2018
- December 2017
- November 2017
- October 2017
- September 2017
- August 2017
- July 2017
- June 2017
- May 2017
- April 2017
- March 2017
- February 2017
- January 2017
- December 2016
- November 2016
- October 2016
- September 2016
- August 2016
- July 2016
- June 2016
- May 2016
- April 2016
- March 2016
- February 2016
- January 2016
- December 2015
- November 2015
- October 2015
- September 2015
- August 2015
- July 2015
- June 2015
- February 2015
- January 2015
- December 2014
- November 2014
- October 2014
- September 2014
- August 2014
- July 2014
- June 2014
- May 2014
- April 2014
- March 2014
- February 2014
- January 2014
- December 2013
- November 2013
- October 2013