Skip to content
Permalink
Branch: master
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
37 lines (33 sloc) 2.19 KB
---
title: "Random Numbers and Seeds in R"
author: "Jason Bryer"
date: 2019-02-17
categories: ["R"]
tags: ["random numbers"]
---
<p>To explore how R generates randome numbers, we will use the <code>rnorm</code> function. This function draws a random number from a normal distribution with a mean = 0 and standard deviation = 1 (though these can be changed with the <code>mean</code> and <code>sd</code> parameters). With <code>n = 1</code> we will get two random numbers.</p>
<pre class="r"><code>rnorm(n = 1)</code></pre>
<pre><code>## [1] -0.1520893</code></pre>
<pre class="r"><code>rnorm(n = 1)</code></pre>
<pre><code>## [1] -0.6202317</code></pre>
<p>Each time you run the command you will get a different number. The <code>set.seed</code> function will sets a seed to the random number generator so that each subsequent run will produce the same number.</p>
<pre class="r"><code>set.seed(2112); rnorm(n = 1)</code></pre>
<pre><code>## [1] 0.9243372</code></pre>
<pre class="r"><code>set.seed(2112); rnorm(n = 1)</code></pre>
<pre><code>## [1] 0.9243372</code></pre>
<p>Setting a different seed results in a different number.</p>
<pre class="r"><code>set.seed(2113); rnorm(n = 1)</code></pre>
<pre><code>## [1] 0.5499032</code></pre>
<p><strong>What are seeds?</strong></p>
<p>Computers are actually bad at random events. However, there are good algorithms that mimic random processes. These algorithms work by starting with some initial value, a seed, and executing a complex algorithm that approximates randomozation. The seed is often set to the current time in miliseconds. To visualize the ramdom process, we will use the <code>sample</code> function to randomly select a number between 1 and 100. We will consider the ouput for the first 1,000 seeds.</p>
<pre class="r"><code>random_numbers &lt;- integer(1000)
for(i in seq_len(length(random_numbers))) {
set.seed(i)
random_numbers[i] &lt;- sample(1:100, size = 1)
}
library(ggplot2)
ggplot(data.frame(x = 1:100, y = random_numbers),
aes(x = x, y = y)) +
geom_point() +
xlab(&#39;Seed&#39;) + ylab(&#39;Random Number&#39;)</code></pre>
<p><img src="/post/2019-02-17-random_numbers_and_seeds_files/figure-html/unnamed-chunk-4-1.png" width="672" /></p>
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.