user1836894
user1836894

Reputation: 301

Counter in an if/else statement using R?

I am relatively new to R and programming in general and I was wondering if there is a way to put a counter inside of an if else statement in my for loop. I have the following if/else statement inside of a for loop:

if(runif(1)<min(1,r)) {
Gibbsalph[,t]=alphcandidate
} else{
Gibbsalph[,t]=Gibbsalph[,t-1]
}

Is there a way to count how many times the loop chose the "if" option (i.e. how many times Gibbsalph[,t]=alphcandidate) while proceeding through the iterations?

Thanks a lot!

Upvotes: 0

Views: 5967

Answers (2)

Carl Witthoft
Carl Witthoft

Reputation: 21532

Here's what you've got now:

if(runif(1)<min(1,r))

Assuming your loop is over the sequence jj = 1:t , how about:

alltests <- runif(t) < min(1,r)  #vector of TRUE, FALSE
wincount <- sum(alltests)

and inside the loop,

Gibbsalph[,t] <- alphcandidate * alltests[jj] + Gibbsalph[,t-1]*(!alltests[jj])

Upvotes: 0

Michael
Michael

Reputation: 5898

This might be useful as it avoids creating the global variable i. see Examples of the perils of globals in R and Stata

init.counter <- function(){
  x <- 0
  function(){
    x <<- x + 1
    x
   }
}  #source: hadley wickham

> counter1 <- init.counter()
> 
> counter1()
[1] 1
> counter1()
[1] 2
> 

To access the value of the counter without iterating it:

environment(counter1)$x

So it would end up as:

counter2 <- init.counter()
if(runif(1)<min(1,r)) {
counter2()
Gibbsalph[,t]=alphcandidate
} else{
Gibbsalph[,t]=Gibbsalph[,t-1]
}
environment(counter2)$x

Upvotes: 3

Related Questions