I am new to R and I have a small issue. I have the following code for my slot machine in R (from the "hands-on programming with R" from Garrett Grolemund.
When I use the play() function for my slot machine that you can see below, I get a single number that tells me how much I have won. When I use the following code to replicate the outcome:
slot.mach <- replicate(1000,play())
R prints all the 1000 examples in my console. What I don't understand is that when I use the same replicate function on my pair of dice that also have one number as an outcome, it does not print all the rolls, but instead just adds them as a vector to my object and I can use qplot right away (that's what I want with my slot machine too).
I obviously don't want all of them printed as it takes a lot of time & space and is unnecessary for me to see all the outcomes.
My guess is that it might have something to do with the class and type of the object, see below:
[1] "integer"
> typeof(slot.mach)
[1] "double"
> class(slot.mach)
[1] "numeric"
> typeof(roll.dice)
[1] "integer"
> class(roll.dice)
[1] "integer"
I don't know whether it's important for you to help me, but here is the whole code for my slot machine:
score <- function(symbols) {
#identify case of symbols frequency
same <- length(unique(symbols)) == 1
bars <- symbols %in% c("B","BB","BBB")
#get prize
if (same) {
payouts <- c("DD" = 100,"7" = 80, "BBB" = 40, "BB" = 25, "B" = 10, "C" = 10,
"0" = 0)
prize <- unname(payouts[symbols[1]])
} else if (all(bars)){
prize <- 5
} else {
cherries <- sum(symbols == "C")
prize <- c(0,2,5)[cherries+1]
}
#adjust for diamonds
diamonds <- sum(symbols == "DD")
prize <- prize*(2^diamonds)
}
Then I can play the function:
play <- function() {
get_symbols <- function() {
wheel <- c("DD","7","BBB","BB","B","C","0")
sample(wheel,size=3,replace=TRUE,
prob=c(0.03,0.03,0.06,0.1,0.25,0.01,0.52))
symbols <- get_symbols()
print(score(symbols))
}
Lastly, I get a print outcome, so every "play()" gives me a number. Usually it's zero, sometimes it's a small amount (you can see the probabilities above).
here's my dice function
roll.dice <- function(){x <- 1:6
y <- c(1/8,1/8,1/8,1/8,1/8,3/8)
dice<-sample(x,size=2,replace=TRUE,prob=y)
sum(dice)}
roll.dice <- replicate(10000,roll.dice())