[R] R 'function' as "subroutine"

Gabor Grothendieck ggrothendieck at gmail.com
Wed Oct 3 16:48:57 CEST 2007

On 10/3/07, Ted Harding <Ted.Harding at manchester.ac.uk> wrote:
> Thanks for the suggestions, Gabor!
> On 03-Oct-07 12:52:51, Gabor Grothendieck wrote:
> > 1.  you could place the commands in a file and source the file each
> > time you want to run it or it might be good enough to place it on the
> > clipboard and then just do source("clipboard")
> Using the file solution is a bit cumbersome for the sort of
> situation I was referring to. Basically, I'll be using R
> exploratively, so entering various sequences of commands.
> Every so often I will think "Ah, I'll probably need that
> block again".
> Since there will usually be several of these, the clip-board
> solution wouldn't work.
> In fact, the way I usually work for this kind of thing is
> to have a "side-window" in which I'm editing a text file,
> and into which I write the R commands I want to keep track
> of (a bit like a rather random partial history). Then, if
> I want to re-use any of these, I can highlight a block with
> the mouse and paste it into the R console.
> So it's a bit like your file solution. This text file can
> also subsequently be used as a source of raw material for
> a properly constructed batch file, which is a bonus.
> However, there are two potential inconveniences:
> 1) pasting with the mouse can be error prone, if one has
>   a "dexterity lapse";
> 2) One may end up scrolling back and forth in the file
>   groping for "that sequence" -- and may end up with
>   one which looks like the one you want, but in fact
>   is different in some essential detail. I've also
>   had that problem where there are many commands like
>     X<-source("AUX12NBX4G001.csv")
>   where choice of filenames has nothing to do with me...
>   Indeed, a "function" replacement of the above could
>   look like
>     sNBX4<-function(){X<<-source("AUX12NBX4G001.csv")}

source is used for R commands, not data.  Maybe you want
read.csv .

Also note that by default source evaluates its input in the global
environment.  See ?source

More information about the R-help mailing list