Open Vodkard opened 4 years ago
Ack! I accidentally started a new issue instead of commenting in the Lab 2 post. So sorry, can't figure out how to move this post over there.
Can you please see if this solves your problem?
More broadly, it is a good question. The solutions use a compound logical statement:
# pick goat door
available.doors <- doors[ ! cars & ! first.pick ]
opened.door <- sample( available.doors, size=1 )
If you think about the order of operations, the expression will evaluate ! cars, then ! first.pick, then find the intersection of both. But each expression has a different data type:
game <- c("goat","car","goat","car","goat")
first.pick <- 1
# logical statement with characters, find cars
game != "car" # T F T F T
# logical statement with numbers, omit first.pick
doors != first.pick # F T T T T
# so it is evaluating:
c( T, F, T, F, T ) & c( F, T, T, T, T )
# which should return:
F F T F T # only true if both true
Using which would translate everything to numbers:
which( game == "car" )
> 2, 4
So the set that we cannot choose would be:
# game <- c("goat","car","goat","car","goat")
# first pick = 1, cars = 2 and 4
cars <- which( game == "car" )
not.available <- c( first.pick, cars ) # c( 1, 2, 4 )
available <- doors[ - not.available ]
# OR
available <- doors[ ! doors %in% not.available ]
Both work (compound logical or all numeric)! I am not sure which is more elegant.
The main insight for me as that you need to always be aware of what data type you are currently working with, and how to correctly manipulate that type. For example, notice the difference between the two statements to drop the doors that are not available, one when it's a logical statement and one when it's numbers representing positions:
# logical statement: returns c( F, T, F, T, F )
not.available <- game == "car"
doors[ not.available ] # subset operators drops anything that is F
# numeric vector: returns c( 2, 4 )
not.available <- which( game == "car" )
doors[ - not.available ] # subset with minus a set of numbers drops those positions
I was running your solution to the 5-door code (3 goats, 2 cars) for a better understanding to tackle part 1 of the lab. I noticed that one time when I ran it, the opened.goat.door was a "car" door. I took a screen shot to show you. I used the exact code from your solution html file. I don't know if this would help, but when I was working on Lab 1 and posted in here, you taught me about the "which" function which solved one of my problems. Would coding this give all the possible car doors in the open-door function when a person picks a goat-door to eliminate the screenshot issue?
which(game == "car")