Card Games

Let’s play some card games. Today we will create a deck of cards using R programming.

There are 52 cards in a deck. And they fall into four suits – Diamonds, Spades, Hearts and Clubs. Each of these suits can have nine numbers (2 – 10), three faces (Jack, Queen and King) or an Ace. For example, a card can be an Ace of Clubs, another may be a four of Hearts etc.

suits <- c("Diamonds", "Spades", "Hearts", "Clubs")
numbers <- c("Ace", "Deuce", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King")

We will use the expand.grid function in R to create a data frame with all combinations of suits and numbers.

deck <- expand.grid(Number = numbers, Suit = suits)

If you print the output from the previous command (as_tibble(deck)), you get the following data frame with 52 rows. The top five rows are shown below.

Number
<fctr>
Suit
<fctr>
AceDiamonds
DeuceDiamonds
ThreeDiamonds
FourDiamonds
FiveDiamonds

It still doesn’t look like cards, as they are separated by the columns of the data frame. So we will paste them into each other and create one deck of 52 entries, as follows.

deck <- paste(deck$Number, deck$Suit)
“Ace Diamonds” “Deuce Diamonds” “Three Diamonds” “Four Diamonds” “Five Diamonds” “Six Diamonds” “Seven Diamonds” “Eight Diamonds” “Nine Diamonds” “Ten Diamonds” “Jack Diamonds” “Queen Diamonds” “King Diamonds” “Ace Spades” “Deuce Spades” “Three Spades” “Four Spades” “Five Spades” “Six Spades” “Seven Spades” “Eight Spades” “Nine Spades” “Ten Spades” “Jack Spades” “Queen Spades” “King Spades” “Ace Hearts” “Deuce Hearts” “Three Hearts” “Four Hearts” “Five Hearts” “Six Hearts” “Seven Hearts” “Eight Hearts” “Nine Hearts” “Ten Hearts” “Jack Hearts” “Queen Hearts” “King Hearts” “Ace Clubs” “Deuce Clubs” “Three Clubs” “Four Clubs” “Five Clubs” “Six Clubs” “Seven Clubs” “Eight Clubs” “Nine Clubs” “Ten Clubs” “Jack Clubs” “Queen Clubs” “King Clubs”

We will do the first two estimations now. How many kings are in the deck, and what is the probability of drawing a king from the deck?

kings <- paste("King", suits) 
deck %in% kings
sum(deck %in% kings) # output is 4
mean(deck %in% kings) # output is 0.07692308


# paste("King", suits) creates all kings (output:  "King Diamonds" "King Spades"   "King Hearts"   "King Clubs" )
# The command, %in%, searches for 'kings' inside the vector 'deck' and returns TRUE or FALSE, depending on whether it matched or not. 
# sum adds up all - each TRUE gets 1, and FALSE gets 0.
# mean gives the average: sum/total count