[R] selectively importing functions etc. from files

Faheem Mitha faheem at email.unc.edu
Sun Nov 30 22:02:48 CET 2008

Hi Charles,

Thanks for the reply.

On Sun, 30 Nov 2008, Charles C. Berry wrote:

> On Sat, 29 Nov 2008, Faheem Mitha wrote:
>> Hi,
>> If I want to import the contents of a R file into another one, I can do
>> source("foo.R")
>> However, this imports everything from foo.R, including all functions 
>> and global variables. Is there a way of selectively importing 
>> individual functions etc., in a similar fashion to Python's
>> from foo import bar
> There are probably a lot of ways to skin this cat.
> But you might want to explain why you want to do this in the first 
> place.

> It may turn out that the problem you wish to solve is better addressed 
> by placing your objects in a package that is attached far down the 
> search list.

Well, I just want to be able to selectively import specific functions from 
files, so I can control what has been imported. One minor advantage of 
this (there are many) is that it makes it difficult to accidentally 
overwrite objects of the same name with each other. This is quite standard 
practice across languages to avoid polluting the global namespace. And of 
course, I'd like to do this as simply as possible.

> A simple way to do what you say you want:
> Use
> 	source("foo.R", local=TRUE)
> from within a function. Then either assign( ..., envir=.GlobalEnv ) 
> selected objects or attach( list( ) ) them.

Not sure I follow this. I want to import into the global namespace. Why 
would I import from within a function? You mean first import locally into 
some function and then selectively export to the global namespace?

> Another way is to use parse, as.character.srcref, and friends to avoid 
> evaluating each of the objects, then eval() selected expressions in the 
> desired environment.

And this one even less. Can you give a simple example?
                                                          Regards, Faheem.

More information about the R-help mailing list