switch statement help in R -
i've got following code in r:
func.time <- function(n){ times <- c() for(i in 1:n){ r <- 1 #x room mouse in x <- 0 #time, starting @ 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, i've been told using switch() can speed seeing i've got many if else statements can't seem work, appreciated in advance.
edit i've tried this:
func.time <- function(n) { times <- c() for(i in 1:n) { r <- 1 #x room mouse in x <- 0 #time, starting @ 0 while(r != 5) { switch(r, "1" = sample(c(2,3), 1), "2" = sample(c(1,3), 1), "3" = sample(c(1,2,4,5), 1), "4" = sample(c(3,5))) x <- x + 1 } times <- c(x, times) } mean(times) } func.time(10000)
but basic attempt, i'm not sure i've understood switch() method properly.
i though dominic's assessment useful when went examine edit being held on thought incorrect basis. decided fix code. when usign numeric argument expr parameter not use item=value formalism rather put in expressions:
func.time <- function(n){times <- c() for(i in 1:n){; r <- 1; x <- 0 while(r != 5){ r <- switch(r, sample(c(2,3), 1) , # r=1 sample(c(1,3), 1) , # r=2 sample(c(1,2,4,5), 1), #r=3 sample(c(3,5), 1) ) # r=4 x <- x + 1 } times <- c(x, times) } mean(times) } func.time(1000) #[1] 7.999
for example of how use switch
numeric argument expr, consider answer question: r switch statement varying outputs throwing error
Comments
Post a Comment