I want to make program that roll dice until some conescutive result. First I write loop:
rolls <- 0
die1 <- 0
die2 <- 0
while(!(die1 == 5 & die2 == 3)) {
die1 <- sample(1:6, 1)
die2 <- sample(1:6, 1)
rolls <- rolls 1
}
print(rolls)
Now I want to make function of this loop and repeat function 100 times:
rolls <- 0
dice <- function(die1 = a, die2 = b){
while(!(die1 == a & die2 == b)) {
die1 <- sample(1:6, 1)
die2 <- sample(1:6, 1)
rolls <- rolls 1
return(rolls)
}}
r1 = replicate(100,dice(5,3))
r2 = replicate(100,dice(6,6))
But I gets error Error in die1 == a & die2 == b : non-conformable arrays
Why this error? How I can fix?
CodePudding user response:
You've set up your function parameters and return value incorrectly. Leave the names off the parameters and move the return()
to outside the loop
dice <- function(a, b){
die1 <- 0
die2 <- 0
rolls <- 0
while(!(die1 == a & die2 == b)) {
die1 <- sample(1:6, 1)
die2 <- sample(1:6, 1)
rolls <- rolls 1
}
return(rolls)
}
r1 = replicate(100,dice(5,3))
r2 = replicate(100,dice(6,6))