Disclaimer: I'm very new to functions in R and really to coding in general.

I'm trying to answer the following question using a simple Monte Carlo sampling procedure in R: An urn contains 10 balls. Two red, three white, and five black. All 10 are drawn one at a time withoutreplacement. Find the probability that both the first and last balls drawn are black.

For whatever reason, my outer for loop indexed by j doesn't seem to be working. My question is twofold: 1) what's wrong with my code, i.e., why doesn't it work to answer the question, and 2) what would the correct code be?

This is what I did:

balls <- c(rep("red", 2), rep("white", 3), rep("black", 5))
counter = 0
counter2 = 0
picks = NULL
keep <- NULL
n = 1000
pick.ball <- function(balls){
sample(x = balls, 1, replace = FALSE)
experiment <- function(n){
for(j in 1:n){
for(i in 1:10){
picks[i] <- pick.ball(balls = balls)
counter= counter + 1
keep[j] <- ifelse(picks[1] == "black" & picks[10] == "black", 1, 0)
counter2 = counter2 + 1
length(which(keep == 1))/n

Also, when do I have to implement the counter function? I've basically just been using it in every for loop where I'm adding something to a vector.

Thanks so much. The help is really appreciated.

  • $\begingroup$ In a round about way I did get the i loop working by changing the balls from names to numbers, which is suboptimal but I suppose solves the initial problem. Now I have balls = c(1:10) and I have an additional line to modify that vector upon sampling of size = 1: balls <- balls[balls != picks[i]] I've also modified the keep[j] line to == any(1:5) for picks[1] and picks[10] so it's all consistent. However, it seems the j loop still doesn't work. $\endgroup$
    – Michael
    Apr 12, 2019 at 20:01

1 Answer 1


In the function pick.ball the collection of balls is not changing at each draw so the loop in i does not simulate a draw without replacement. I suggest you draw all balls at once using sample without replacement rep=FALSE which amounts to simulating a random permutation of the balls and check whether or not the first and last are black.

Note also that the counters are useless as defined since they only reproduce the length of their respective loop.

  • $\begingroup$ I originally had size = 10 for the sample function to pick all the balls at once but that lead to the following warning repeated 10 times: In picks[i] <- pick.ball(balls = balls) : number of items to replace is not a multiple of replacement length Is the problem that picks[i] isn't specified as a matrix? Alternatively, I'm not sure how in the i loop I would code removing the chosen ball from the urn. I tried a couple things earlier but they just removed all balls of the same color that was chosen. $\endgroup$
    – Michael
    Apr 12, 2019 at 14:40

Not the answer you're looking for? Browse other questions tagged or ask your own question.