Rather than using the global variable counter in R's global environment, use a closure, in other words, lexical scoping, to manage a "private" variable that keeps the count of the number of times find Next Position() is called. You do this by creating a function that returns a list with two functions. One of these functions increments the counter variable. The other function returns the current value of that counter. You can also add a third function that resets the counter. Use the incrementing function with trace () to count the number of calls to find Next Position ().