[R] R 'function' as "subroutine"
Gabor Grothendieck
ggrothendieck at gmail.com
Wed Oct 3 14:52:51 CEST 2007
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")
2. Thomas Lumley's defmacro in R News 1/3 could be used
Neither of these two require that you do anything special to write back
the variables.
Although not specifically a solution the problem you pose
look at ?within (new in R 2.6.0) just in case.
On 10/3/07, Ted Harding <Ted.Harding at manchester.ac.uk> wrote:
> Hi Folks,
>
> The question I'm asking, regarding the use of function
> definitions in the context described below, is whether
> there are subtle traps or obscure limitations I should
> watch out for. It is probably a rather naive question...
>
> Quite often, one has occasion to execute interactively
> a lot of R commands in which, from time to time, one has
> occasion to repeat exactly a sequence of commands which
> one has entered earlier. These commands would only refer
> to variables which have been created at the "top level" of
> the program and which exist at the time the sequence of
> commands is entered.
>
> So it would be convenient to refer to such a sequence of
> commands as a "named block" -- just give its name, and
> they are executed.
>
> In my experiments, wrapping the first occurrence of such
> a sequence in a function definition seems to work, e.g.
> the first time they are needed:
>
> block1 <- function(){
> sequence of commands that you would have enetered
> for execution at this point
> }
> block1()
>
> This first call to block1() seems to work OK, in my tests,
> PROVIDED, of course,
> a) The variables it uses and assigns to exist already;
> b) all internal "<-" assignments are written "<<-".
> Then, of course, the next time that block is needed,
> you can call block1() again.
>
> But can this usage of function definition give rise
> to problems? R scoping can be a bit tricky! And I
> think I am perhaps being naive ...
>
> (It is not intended that such blocks of code would include
> function definitions).
>
> OR: Is there a more "kosher" way to do this kind of thing ... ?
>
> With thanks,
> Ted.
>
> --------------------------------------------------------------------
> E-Mail: (Ted Harding) <Ted.Harding at manchester.ac.uk>
> Fax-to-email: +44 (0)870 094 0861
> Date: 03-Oct-07 Time: 12:56:42
> ------------------------------ XFMail ------------------------------
>
> ______________________________________________
> 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