[R] source() vs attach()0

Duncan Murdoch murdoch at stats.uwo.ca
Tue Nov 10 19:35:11 CET 2009


On 11/10/2009 11:14 AM, Stefan Zeugner wrote:
> Hello,
> After hours of googling I could not resolve the following (although it 
> seems simple):
> 
> I would like to put subfunctions in a separate .R file that is then 
> called with source() from inside several "main" functions. A crude 
> example would be as follows:
> 
> **** file subtest.R **********
> subtest <- function() {
>   foo <<- foo+1
>   }
> ******************************
> 
> 
> *** main function ************
> test<-function(foo) {
>   source("test.R",local=TRUE)
>   subtest()
>   return(foo)
>   }
> ******************************
> 
> Then executing the code
>  > test(1)
> works as prescribed.
> But of course, each function call to test() 'sources' (i.e. parse() and 
> eval()) the file subtest.R again and again. (try e.g. changing line 2 in 
> subtest.R to 'foo<<- foo +2' and run 'test(1)' )
> 
> 
> How can I 'attach' the function subtest inside the main function, such 
> that it is not evaluated again at each function call?

Just declaring it there is the only reasonable way, i.e.

test<-function(foo) {
   subtest <- function() {
      foo <<- foo+1
   }
   subtest()
   return(foo)
}

The reason you can't somehow assign it within an existing test is that 
subtest is a different closure every time.  Its environment will be the 
local frame of the call to test, so the "foo" on the right hand side of 
the assignment will be the value that was passed to test.

An unreasonable way to get what you want is to mess with the 
environment, e.g.

subtest <- function() {
    foo <<- foo+1
}

test <- function(foo) {
    mysubtest <- subtest  # make a local copy
    environment(mysubtest) <- environment()  # attach the local frame

    mysubtest()
    return(foo)
}

This is ugly programming, likely to bite you at some future date.

Duncan Murdoch

> 
> And this while maintaining the above 'subfunction' functionality (i.e. 
> attaching the subfunction under the right environment)?
> 
> I was not able to resolve that - thanks in advance for any help!
> 
> all the best
> Stefan
> 
> ______________________________________________
> 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