[R] R 'function' as "subroutine"
(Ted Harding)
Ted.Harding at manchester.ac.uk
Wed Oct 3 13:56:45 CEST 2007
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 ------------------------------
More information about the R-help
mailing list