[R] Variable scope in a function

thatsanicehatyouhave at mac.com thatsanicehatyouhave at mac.com
Tue Sep 4 18:05:03 CEST 2007


Hello,

I apologise in advance for this question; I'm sure it is answered in  
the documentation or this mailing list many times, however the answer  
has eluded me.

I'm trying to write a function where I don't want external variables  
to be scoped in from the parent environment. Given this function:

test_func = function() {

	if (exists("kat") == FALSE) {
		print("kat is undefined")	
	} else {
		print(kat)
	}
}

If I did this:

 > kat = 12
 > test_func()

I'd like the result to be the error, but now it's 12 (which is of  
course correct according to the documentation).

So there are two questions:

1) How can I disregard all variables from the parent environment  
within a function? (Although from what I've read on the mailing lists  
this isn't really what I want.)

Apparently

environment(test_func) = NULL

is defunct, and what I thought was its replacement

environment(test_func) = emptyenv()

doesn't seem to be.


2) How can I "undefine" a variable, perhaps just within the context  
of my function. I'm hoping to find some line that I can put at the  
start of my function above so that the result would be:

 > kat = 12
 > test_func()
[1] "kat is undefined"
 > kat
[1] 12

Thanks in advance for any help!

Cheers,

Demitri



More information about the R-help mailing list