[R] Problem with a global variable

Duncan Murdoch murdoch at stats.uwo.ca
Tue Dec 4 12:37:38 CET 2007


On 04/12/2007 12:51 AM, Thomas L Jones, PhD wrote:
> From: Thomas Jones
> 
> I have several user-defined functions. As is standard practice, I am 
> defining a logical vector named idebug in order to control debugging 
> printouts. For example, if idebug [1] has the value TRUE, such-and-such 
> debugging printouts are enabled. After the function works, some or all of 
> the debugging printouts can be inhibited. idebug is a global variable; 
> otherwise, it would have to be moved around with function arguments in a way 
> which is clunky and hard to get right. However, I am getting an error 
> message. This message was emitted during the loading of the program and is 
> NOT inside any function.
> 
> Or perhaps idebug wants a special slot on the search path.
> 
> -------------------------------------------------------------------
> 
>> debug_l <- 5 # length of debug vector
>> idebug <<- logical (5)
>> idebug [1] <<- TRUE
> Error in idebug[1] <<- TRUE : object "idebug" not found
> [snip]
> ---------------------------------------------------------------
> 
> Your advice?

Don't use <<- at the top level.  Use regular assignment, and things 
should be fine.

What is happening in your case is this:

1.  idebug <<- logical(5)

looks for idebug in the parents of the global environment, fails to find 
it, and creates a new one in the global environment.


2.  idebug[1] <<- TRUE

looks for idebug in the parents again, but this time it needs to find 
it, because you are trying to index it.  That's why you get an error on 
the second call.

Duncan Murdoch



More information about the R-help mailing list