Question

I'm trying to run a function much more complex but equal to:

 A <<- 5
 B <<- 5

table <- data.frame(A,B)
backup <- table

test <- function(A,B){
 while(A > 0){
    r <- runif(1,0,1)
    if ((r >= 0)&(r <= 0.5)){
        A <- A + 1
        B <- B - 1
    } else if ((r > 0.5)&(r<=1)){
          A <- A - 1
          B <- B + 1
          }

 tab <- cbind(A,B)
 table <<- rbind(table,tab)

 if (nrow(table) == 10) {
     break
     } else  if ((A > 0) & (nrow(table) != 10)) {
          next
     } else {if ((A == 0) & (nrow(table != 10)) {   #pointing to error here?
         A <- 5
          B <- 5
        table <- backup
       next
    }
}
}

So what I want this function to do is stop when the when number of rows of the table (= the number of times the function ran) is equal to a certain value, in this case 10. But A cannot take a value below 0. If A reaches 0 before the number of rows of the table is 10 the whole process has to start again, with the same inputvalues as before.

However, this function does not work. I think it's because I use multiple next statements, is that correct?

Thanks!

Was it helpful?

Solution

I think you're on the right track... just a few recommendations

I think this accomplishes what you're trying to achieve a little cleaner. I second Carl's suggestion of avoiding the global operator '<<-' when possible and passing the objects through to the function as arguments or parameters. I also second Justin's suggestion of avoiding the break command in favor of placing the return() call smartly. To accomplish this, I put your 10 (stopping criteria) directly into the while loop. I included it as a parameter n so that you can experiment with different stopping criteria. Hope this helps :)

test <- function(A,B,n){
  A0 <- A
  B0 <- B
  tab <- data.frame(A,B)
  while(A > 0 & nrow(tab) < n){
    r <- runif(1,0,1)
    if (r <= 0.5){
      A <- A + 1
      B <- B - 1
    } else {
      A <- A - 1
      B <- B + 1
    }

    tab1 <- cbind(A,B)
    tab <- rbind(tab,tab1)

    if(nrow(tab)<n & A==0){
      A<-5
      B<-5
      tab <- cbind(A0,B0)
      names(tab) <- c('A', 'B')
      print(paste('found A==0 in less than ', n, ' iterations', sep=''))
    } 
  }
  return(tab)
}

Testing function...

## running function
A <- 5
B <- 5
testDF <- test(A,B,10)

> testDF 
    A B
1   5 5
2   6 4
3   5 5
4   6 4
5   7 3
6   8 2
7   9 1
8  10 0
9   9 1
10 10 0
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top