Jim_dddd Jim_dddd - 2 months ago 7
R Question

Calculate probabilities in R programming

I'm new to R and I'm doing a practice question on it.
Calculate the probability of drawing two face cards (Jack, Queen, King) in a row.
Simulate a standard deck of 52 cards (no Jokers). Sample two cards from the deck 1000 times (remember, we do not replace the card after drawing). How does the proportion of times two face cards were drawn compare to the probability you calculated?
This is what I tried:

poker <- c(1:10, "J", "Q", "K")

poker_face <- sample(poker, size = 1000, replace = FALSE)

it gives me:

Error in sample.int(length(x), size, replace, prob) : cannot take a
sample larger than the population when 'replace = FALSE'


I think this is what you really want:

poker_face <- replicate(1000, sample(poker, size =2, replace = FALSE))

You want to repeat the experiment 1000 times, not sample 1000 cards without replacement from a deck. So there is a conceptual misunderstanding here. replicate above would give you a matrix of 2 rows and 1000 columns, where each column is the result of one out of 1000 experiments.

To compute the probability you want, you need the number of simulations that give you face cards. How about:

m <- sum(colSums(matrix(poker_face %in% c("J", "Q", "K"), nrow = 2)) == 2)

Then m/1000 is the estimated probability based on your simulations.