Sunday, November 17, 2019

Lesson 8: Random Number Generator - Part 1

Lesson 8: Random Number Generator - Part 1

Introduction

This lesson is part one of a two part lesson with the ultimate goal of building a Shiny Application.
In this lesson we’re going to learn how to make a very simple random number generator using basic R functions. You’ll be able to specify how many random values you’d like to get overa specified range. Additionally, you’ll be able to specify whether or not you’d like the number removed from the range once drawn or if you’d lke to leave it in to potentially be drawn again.
After we’ve built this script, we’ll go to the next lesson and build the Shiny Application based on your code which we’ll then deploy as a web application!
I know! Cool, Right!?

Part 1 - The Random Number Generator

The first thing we need to determine is how many randomly selected values does the user need? We will assign this to a variable called “values”. Also, we’ll need to know over what range of numbers should the values be randomly selected. So, we’ll ask the user to provide a “Start” and “End” value for the range of numbers of interest. We will assign these values to “rangeStart” and “rangeEnd”
As I mentioned earlier, sometimes when you’re drawing numbers randomly you pull the number and it stays out of consideration on future draws. This is called sampling without replacement. Other times you draw the number and then put it back in the mix for future consideration where it could be drawn again. This is called sampling with replacement. We will simulate this capability by adding a variable called “dupes”. The “dupes” variable will allow the user to decide if they want to allow the possibility for duplicate random values or if they want each number drawn to be unique over the specified range of values.
Next, we can verify that we have the correct range of numbers we need by creating a variable called “numbers”. The “numbers” variable will actually be a sequence of values created using R’s “seq” funtion starting at “rangeStart” and ending at “rangeEnd”.
## [1] 1 2 3 4
Now that we have all the main components for our script we’ll assemble them using one of R’s built-in or “base” functions called “sample”. Sample does just that, it samples the provided data randomly. We just have to provide the range of values, the number of values to randomly pick from it, and specify whether or not we desire the values replaced back into the range of values after being drawn.
## [1] 1 2 4 3

That’s it!

Now that you’ve got your very own handy-dandy number generator, you’ll be ready to take it to the next level and turn it into a web application that can be shared around the world using a Shiny App. We’re going to tackle that in the next Lesson!

Enjoy!

Have fun coding!

RDataGuy

Download the code for this lesson below!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.