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 ? Thanks in advance. Please cc me on any reply. Regards, Faheem.
Charles C. Berry
2008-Nov-30 18:38 UTC
[R] selectively importing functions etc. from files
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 barThere 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. 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. 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. HTH, Chuck> > ? Thanks in advance. Please cc me on any reply. > Regards, Faheem. > > ______________________________________________ > 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. >Charles C. Berry (858) 534-2098 Dept of Family/Preventive Medicine E mailto:cberry at tajo.ucsd.edu UC San Diego http://famprevmed.ucsd.edu/faculty/cberry/ La Jolla, San Diego 92093-0901