An introduction to R

From GEST-S482 Digital Business
Jump to navigation Jump to search

R is a programming language built for data and statistical analysis. It was developed by Robert Gentleman and Ross Ihaka at the University of Auckland (New Zealand) in 1992.

The language is an open-software available to everyone. It is used a lot by statisticians, bioinformatics, and others.

R can be used as a calculator using the following basic arithmetic: Example:

 > 9+5  = 14 
 > 9-5  = 4 
 > 9*5  = 45
 > 6/3  = 2


You can also assign data to an R object: Example:

 > a  = 9 
 > a  = 5 

And use it to calculate the same computations as before.

 > a+b  = 14 
 > a*b  = 45 

You can create lists as follow:

list <- 1:6 = 1 2 3 4 5 6 

Isn't it fun to use R as a calculator?

Of course, R can be used for far more interesting results. We will discover more of them later. I will show you how to build a weighted dice with R. It will be helpful when you will play with your friend the famous board game "Risk". In that game, you need to throw the dice hundreds of times. thanks to R, you will now have a way to save a lot of your precious time to think more about your strategies to win the game.

-The creation of a trio of fair weighted probability dice-

-Let's process step by step:

  1. Turn on "RStudio". (An internet connection is required)
  2. Install (if it is not done yet) the required packages:
 > install.packages("ggplot2")
  1. Load the packages previously installed
 > library("ggplot2")
  1. create the "die" function:
 > die <- 1:6
  1. add it to the a new function including the three dice;
 >   die <- 1:6
 >   dice <- sample (die, size = 3, replace = TRUE)
  1. sum them up
 >   die <- 1:6
 >   dice <- sample (die, size = 3, replace = TRUE)
 >   sum(dice)
  1. add everything up to the function "roll":
 > roll <- function() {
 >   die <- 1:6
 >   dice <- sample (die, size = 3, replace = TRUE)
 >   sum(dice)
 > } 
  1. Now, you want to change the fair probability to weighted probabilities because you want to win the game against your friends. Add the probabilities for each face of the die.
 > roll <- function() {
 >   die <- 1:6
 >   dice <- sample (die, size = 3, replace = TRUE, prob = c(1/100, 1/100, 1/100, 1/100, 1/100, 95/100)
 >   sum(dice)
 > } 

Next time, we will learn how to create a deck of 52 cards to see how the card games work. The first game we will build is called: "Royal Flush". Do you know it? Have you plaid before?