ts3n_mt
ts3n_mt

Reputation: 67

Write a function that randomly draws five cards from the deck in R (full explanation)

"Please create a deck of cards and store the face, suit and value information in a data frame. Write a function that randomly draws five cards from the deck."

This is my code for the data frame

    suit<-c("clubs","diamonds", "hearts", "spades")
    face<-c("king", "queen", "jack", "ten", "nine", "eight", "seven", "six", "five", "four", "three", "two", "ace")
    num<-c(13, 12,11,10,9,8,7,6,5,4,3,2,1)
    deck <-data.frame(face=rep(face,4),
                      suit=c(rep("spades", 13), rep("clubs", 13), rep("diamonds", 13), rep("hearts", 13)),
                      num=rep(num,4))

This is code @Ronak came up with

    draw_n_random_cards <- function(deck, n) {
  deck[sample(nrow(deck), n), ]
}

set.seed(123)
result <- draw_n_random_cards(deck, 5)
result

Is my understanding of this code correct?

**1. Created a function called “draw_n_random_cards with arguments “deck” and “n.”

**2. The code for the function uses notation [sample(nrow(deck), n,] to work within the deck for drawing random cards. “Nrow” returns the number of rows in data frame “deck” and “n” as the size of the same. “Nrow” returns the 52 rows of the deck and “n” will draw cards from the 52 rows.

3. Set.seed() function allows the same sample to be reproduced each time and get the same results for the same seed number (123).

#4. “Result” is going to run the random sample for 5 cards. Is this the correct logic?

My last question is: even if I run the “result” object w/o the seed(123) function, the 5 cards are the same on the output (face, suit, number are the same). How would I generate a new set of 5 random cards, if I choose too?

Upvotes: 1

Views: 1439

Answers (2)

akrun
akrun

Reputation: 887223

We can use sample_n from dplyr

library(dplyr)
deck %>%
   sample_n(5)

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 389047

You can use sample to select n random cards.

draw_n_random_cards <- function(deck, n) {
  deck[sample(nrow(deck), n), ]
}

set.seed(123)
result <- draw_n_random_cards(deck, 5)
result

#    face     suit num
#31  nine diamonds   9
#15 queen    clubs  12
#14  king    clubs  13
#3   jack   spades  11
#42  jack   hearts  11

Upvotes: 2

Related Questions