vendredi 20 mars 2015

switch statement help in R

I've got the following code in R:



func.time <- function(n){
times <- c()
for(i in 1:n){

r <- 1 #x is the room the mouse is in
X <- 0 #time, starting at 0
while(r != 5){

if(r == 1){
r <- sample(c(2,3),1) }

else if(r == 2){
r <- sample(c(1,3), 1) }

else if(r == 3){
r <- sample(c(1,2,4,5), 1) }

else if (r == 4){
r <- sample(c(3,5), 1) }

X <- X + 1
}

times <- c(X, times)
}
mean(times)
}
func.time(10000)


It works fine, but I've been told that using switch() can speed it up seeing as I've got so many if else statements but I can't seem to get it to work, any help is appreciated in advance.


Aucun commentaire:

Enregistrer un commentaire