R语言swirl教程(R Programming)13——Simulation

R语言swirl教程(R Programming)13——Simulation

| One of the great advantages of using a statistical programming language like R is its vast collection of tools for simulating random numbers.

| This lesson assumes familiarity with a few common probability distributions, but these topics will only be discussed with respect to random number generation. Even if you have no prior experience with these concepts, you should be able to complete the lesson and understand the main ideas.

| The first function we’ll use to generate random numbers is sample(). Use ?sample to pull up the documentation.

?sample

| Let’s simulate rolling four six-sided dice: sample(1:6, 4, replace = TRUE).

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

| Now repeat the command to see how your result differs. (The probability of rolling the exact same result is (1/6)^4 = 0.00077, which is pretty small!)

sample(1:6, 4, replace = TRUE)
[1] 4 5 3 1

| sample(1:6, 4, replace = TRUE) instructs R to randomly select four numbers between 1 and 6, WITH replacement. Sampling with replacement simply means that each number is “replaced” after it is selected, so that the same number can show up more than once. This is what we want here, since what you roll on one die shouldn’t affect what you roll on any of the others.

| Now sample 10 numbers between 1 and 20, WITHOUT replacement. To sample without replacement, simply leave off the ‘replace’ argument.

sample(1:20, 10)
[1] 1 8 7 17 6 13 20 10 2 4

| Since the last command sampled without replacement, no number appears more than once in the output.

| LETTERS is a predefined variable in R containing a vector of all 26 letters of the English alphabet. Take a look at it now.

LETTERS
[1] “A” “B” “C” “D” “E” “F” “G” “H” “I” “J” “K” “L” “M” “N” “O” “P” “Q” “R” “S” “T” “U” “V” “W” “X” “Y” “Z”

| The sample() function can also be used to permute, or rearrange, the elements of a vector. For example, try sample(LETTERS) to permute all 26 letters of the English alphabet.

sample(LETTERS)
[1] “U” “I” “G” “Q” “R” “X” “M” “C” “W” “K” “H” “J” “A” “F” “L” “N” “V” “Z” “T” “D” “O” “P” “S” “B” “E” “Y”

| This is identical to taking a sample of size 26 from LETTERS, without replacement. When the ‘size’ argument to sample() is not specified, R takes a sample equal in size to the vector from which you are sampling.

| Now, suppose we want to simulate 100 flips of an unfair two-sided coin. This particular coin has a 0.3 probability of landing ‘tails’ and a 0.7 probability of landing ‘heads’.

| Let the value 0 represent tails and the value 1 represent heads. Use sample() to draw a sample of size 100 from the vector c(0,1), with replacement. Since the coin is unfair, we must attach specific probabilities to the values 0 (tails) and 1 (heads) with a fourth argument, prob = c(0.3, 0.7). Assign the result to a new variable called flips.

flips <- sample(c(0, 1), 100, replace = TRUE, prob = c(0.3, 0.7))

| View the contents of the flips variable.

flips
[1] 0 1 1 0 1 1 1 0 0 1 0 1 1 1 1 1 0 1 1 1 1 1 1 1 1 0 1 0 1 1 0 1 0 0 0 0 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 1 1
[55] 1 1 1 1 1 0 1 0 1 1 1 1 1 0 0 0 1 0 1 1 1 1 0 0 0 0 1 1 1 1 1 1 1 1 1 0 1 1 0 1 1 1 1 1 1 0

| Since we set the probability of landing heads on any given flip to be 0.7, we’d expect approximately 70 of our coin flips to have the value 1. Count the actual number of 1s contained in flips using the sum() function.

sum(flips)
[1] 72

| A coin flip is a binary outcome (0 or 1) and we are performing 100 independent trials (coin flips), so we can use rbinom() to simulate a binomial random variable. Pull up the documentation for rbinom() using ?rbinom.

?rbinom

| Each probability distribution in R has an r*** function (for “random”), a d*** function (for “density”), a p*** (for “probability”), and q*** (for “quantile”). We are most interested in the r*** functions in this lesson, but I encourage you to explore the others on your own.

| A binomial random variable represents the number of ‘successes’ (heads) in a given number of independent ‘trials’ (coin flips). Therefore, we can generate a single random variable that represents the number of heads in 100 flips of our unfair coin using rbinom(1, size = 100, prob = 0.7). Note that you only specify the probability of ‘success’ (heads) and NOT the probability of ‘failure’ (tails). Try it now.

rbinom(1, size = 100, prob = 0.7)
[1] 71

| Equivalently, if we want to see all of the 0s and 1s, we can request 100 observations, each of size 1, with success probability of 0.7. Give it a try, assigning the result to a new variable called flips2.

flips2 <- rbinom(n = 100, size = 1, prob = 0.7)

| View the contents of flips2.

flips2
[1] 1 1 1 1 0 0 1 0 0 1 0 0 0 1 1 1 0 1 1 1 0 0 1 1 1 1 1 0 1 1 0 1 1 0 0 1 1 1 1 0 1 1 1 0 1 1 1 0 1 0 0 1 1 1
[55] 0 1 0 0 1 1 0 1 1 0 0 0 1 0 1 0 0 1 1 1 1 0 1 1 1 1 0 0 1 1 0 0 0 1 0 0 1 1 1 1 1 0 1 1 1 1

| Now use sum() to count the number of 1s (heads) in flips2. It should be close to 70!

sum(flips2)
[1] 62

| Similar to rbinom(), we can use R to simulate random numbers from many other probability distributions. Pull up the documentation for rnorm() now.

?rnorm

| The standard normal distribution has mean 0 and standard deviation 1. As you can see under the ‘Usage’ section in the documentation, the default values for the ‘mean’ and ‘sd’ arguments to rnorm() are 0 and 1, respectively. Thus, rnorm(10) will generate 10 random numbers from a standard normal distribution. Give it a try.

rnorm(10)
[1] 0.03805885 1.46409783 0.51065848 1.25191388 -0.11820322 0.54497581 -0.51056602 0.35439295 -1.78820160
[10] -0.91448535

| Now do the same, except with a mean of 100 and a standard deviation of 25.

rnorm(10, 100, 25)
[1] 81.00325 81.57364 126.88820 76.44777 89.06077 95.70729 108.13601 85.79808 86.91337 101.37374

| Finally, what if we want to simulate 100 groups of random numbers, each containing 5 values generated from a Poisson distribution with mean 10? Let’s start with one group of 5 numbers, then I’ll show you how to repeat the operation 100 times in a convenient and compact way.

| Generate 5 random values from a Poisson distribution with mean 10. Check out the documentation for rpois() if you need help.

?rpois
rpois(5, 10)
[1] 6 11 12 12 11

| Now use replicate(100, rpois(5, 10)) to perform this operation 100 times. Store the result in a new variable called my_pois.

my_pois <- replicate(100, rpois(5, 10))

| Take a look at the contents of my_pois.

my_pois
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [,15] [,16] [,17] [,18] [,19]
[1,] 10 9 9 9 12 11 15 10 11 9 13 5 9 15 6 10 16 7 11
[2,] 12 10 9 11 7 7 12 18 10 5 19 12 13 10 15 10 14 13 9
[3,] 10 8 9 13 18 7 12 15 8 11 13 14 8 10 7 16 6 13 9
[4,] 17 15 13 14 8 10 5 12 8 14 11 12 7 7 12 11 8 8 6
[5,] 10 12 8 10 11 12 17 6 11 9 11 14 4 11 8 15 8 10 10
[,20] [,21] [,22] [,23] [,24] [,25] [,26] [,27] [,28] [,29] [,30] [,31] [,32] [,33] [,34] [,35] [,36] [,37]
[1,] 12 10 9 20 6 10 14 12 11 14 10 6 11 12 7 9 8 10
[2,] 11 4 3 12 11 9 8 10 10 9 5 7 6 8 7 7 4 6
[3,] 9 8 8 14 6 11 8 9 11 12 4 8 12 15 15 14 10 17
[4,] 9 13 7 8 13 7 6 8 12 4 8 13 10 9 6 9 11 8
[5,] 9 10 7 15 12 11 14 9 11 14 9 13 9 12 9 13 10 12
[,38] [,39] [,40] [,41] [,42] [,43] [,44] [,45] [,46] [,47] [,48] [,49] [,50] [,51] [,52] [,53] [,54] [,55]
[1,] 9 7 12 14 17 16 5 16 11 5 11 11 6 19 5 9 5 7
[2,] 10 12 13 9 12 9 12 12 11 9 14 8 14 12 7 9 13 10
[3,] 12 7 9 11 8 13 14 10 8 12 11 11 13 6 8 5 10 14
[4,] 16 8 15 5 8 11 10 10 10 13 16 15 12 10 14 6 13 9
[5,] 9 8 8 9 13 7 13 9 9 13 8 10 9 8 9 16 5 14
[,56] [,57] [,58] [,59] [,60] [,61] [,62] [,63] [,64] [,65] [,66] [,67] [,68] [,69] [,70] [,71] [,72] [,73]
[1,] 14 15 6 7 8 10 10 8 9 9 10 15 12 15 11 15 14 10
[2,] 10 6 9 6 9 12 10 12 6 13 8 9 21 14 6 10 7 10
[3,] 6 13 8 13 5 7 10 12 15 10 7 8 11 12 7 13 11 10
[4,] 7 9 12 12 12 11 14 10 8 12 11 9 7 16 15 10 6 19
[5,] 7 15 9 11 11 12 13 11 11 5 13 5 13 10 11 11 7 17
[,74] [,75] [,76] [,77] [,78] [,79] [,80] [,81] [,82] [,83] [,84] [,85] [,86] [,87] [,88] [,89] [,90] [,91]
[1,] 12 15 13 17 13 8 8 15 8 8 6 6 14 14 13 13 9 13
[2,] 11 10 10 20 8 12 13 7 6 12 15 12 10 8 16 13 5 8
[3,] 9 12 8 9 12 10 11 9 10 15 3 10 12 13 11 13 10 10
[4,] 15 15 13 5 9 16 11 8 7 13 9 13 7 15 11 12 13 10
[5,] 14 13 10 16 10 7 8 10 9 12 3 14 11 13 10 13 9 9
[,92] [,93] [,94] [,95] [,96] [,97] [,98] [,99] [,100]
[1,] 12 9 2 9 14 7 8 6 12
[2,] 8 5 6 8 6 10 10 8 11
[3,] 9 12 11 7 14 10 8 9 7
[4,] 5 9 5 11 8 7 12 6 10
[5,] 9 10 14 10 17 5 16 6 7

| replicate() created a matrix, each column of which contains 5 random numbers generated from a Poisson distribution with mean 10. Now we can find the mean of each column in my_pois using the colMeans() function. Store the result in a variable called cm.

cm <- colMeans(my_pois)

| And let’s take a look at the distribution of our column means by plotting a histogram with hist(cm).

hist(cm)
在这里插入图片描述

| Looks like our column means are almost normally distributed, right? That’s the Central Limit Theorem at work,| but that’s a lesson for another day!

| All of the standard probability distributions are built into R, including exponential (rexp()), chi-squared (rchisq()), gamma (rgamma()), … Well, you see the pattern.

| Simulation is practically a field of its own and we’ve only skimmed the surface of what’s possible. I encourage you to explore these and other functions further on your own.

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值