[R] can I call user-created functions without source() ?

Joerg van den Hoff j.van_den_hoff at fz-rossendorf.de
Mon Jun 19 17:30:27 CEST 2006


Duncan Murdoch wrote:
> On 6/19/2006 10:19 AM, Joerg van den Hoff wrote:
>> Duncan Murdoch wrote:
>>> Just a few comments below on alternative ways to do the same things:
>>>
>>> On 6/19/2006 8:19 AM, Joerg van den Hoff wrote:
>>>
>>>> for short term usage of some specialized functions I have added some 
>>>> lines to the `.Rprofile' in my home(!) directory as follows 
>>>> (probably there are smarter solutions, but at least it works):
>>>>
>>>> #source some temporary useful functions:
>>>> fl <- dir(path='~/rfiles/current',patt='.*\\.R$',full.names=TRUE)
>>>> for (i in fl) {cat(paste('source("',i,'")\n',sep="")); source(i)}
>>>> rm(i,fl)
>>>
>>> Another way to do this without worrying about overwriting some 
>>> existing variables is
>>>
>>> local({
>>> fl <- ...
>>> for (i in fl) ...
>>> })
>>
>>>
>>> No need to remove fl and i at the end; they were created in a 
>>> temporary environment, which was deleted at the end.
>>>
>> sure, that's better (just one more case, where I did'nt know of the 
>> existence of a certain function). but what is the difference (with 
>> regards to scope) of `i' or `fl' and the functions defined via 
>> sourcing? are'nt both objects defined within `local'? why _are_ the 
>> functions visible in the workspace? probably I again don't understand 
>> the `eval'/environment intricacies.
> 
> Whoops, sorry.  Yes, you'd need to be careful to assign them into 
> globalenv().  Those ...'s weren't so simple.
> 
no, no, you _were_ right (I tested it), but I did'nt understand why it 
works. I found the answer only now in the `source' manpage: there is an 
argument `local = FALSE' which by default enforces assignment into 
globalenv(). so the `...' remain unaltered :-). sorry for the confusion.

joerg

PS: and as a follow up on the recent 'setwd vs. cd' thread: as I noted 
in passing `source' has a further argument `chdir' to change the 
directory prior to sourcing, which is neither the usual name (using 
`cd') nor the R-way (using `setwd'), but rather identical to the 
corresponding native matlab/octave command (both of these packages have 
for quite some time changed to accepting `cd' as well). of course, the 
`source' arguments have nothing to do with the commands but consistency 
would'nt harm either :-). not important, but a bit funny.

> Duncan Murdoch



More information about the R-help mailing list