[R] Warning when trying to access a variable out of scope?

Greg Snow Greg.Snow at imail.org
Fri Jul 3 21:28:11 CEST 2009


Does this do what you want?

> b.test <- 3
> 
> f <- function(a,b) {
+ a+b.test
+ }
> 
> f(10,20)
[1] 13
> 
> environment(f) <- baseenv()
> 
> f(10,20)
Error in f(10, 20) : object 'b.test' not found
> 
>


-- 
Gregory (Greg) L. Snow Ph.D.
Statistical Data Center
Intermountain Healthcare
greg.snow at imail.org
801.408.8111


> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
> project.org] On Behalf Of Steve Lianoglou
> Sent: Thursday, July 02, 2009 12:17 PM
> To: R-help at r-project.org
> Subject: [R] Warning when trying to access a variable out of scope?
> 
> Hi,
> 
> I was wondering if I could get R to warn me, or give me a rude
> awakening somehow, if I'm accessing a variable that is out of my
> function's scope.
> 
> For example, often times I'm creating a function as I'm testing it in
> the REPL, copying and pasting between both.
> 
> As a simple example, I might end up with a function like:
> 
> f <- function(a, b) {
>    a + b.test
> }
> 
> Where b.test was defined in my workspace as I'm mucking about in the
> REPL, but "clearly" I should have written:
> 
> f <- function(a,b) {
>    a + b
> }
> 
> I could go on for a while in my session w/o noticing the problem
> (since b.test is in my global env), and unbeknownst to me, my function
> will keep accessing the "b.test" variable when I really want it to
> work on the "b" var that I'm passing in to it.
> 
> Is there some setting or someway I can get R to warn me that "b.test"
> is being accessed outside the scope of my function?
> 
> Thanks,
> -steve
> 
> --
> Steve Lianoglou
> Graduate Student: Physiology, Biophysics and Systems Biology
> Weill Medical College of Cornell University
> 
> Contact Info: http://cbio.mskcc.org/~lianos/contact
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-
> guide.html
> and provide commented, minimal, self-contained, reproducible code.




More information about the R-help mailing list