[R] Echoing commands (not using source())

Prof Brian D Ripley ripley at stats.ox.ac.uk
Wed Apr 11 08:42:28 CEST 2001


On Tue, 10 Apr 2001, Henrik Bengtsson wrote:

> Is there a way of echoing (similar to Matlab "echo on") commands that are
> being executed? I know how to do this for script files by using source(...,
> echo=TRUE), but I would like to be able to use this within *any* function. I

One problem is that is not that what source(..., echo = TRUE does). It echo
expressions at the prompt level, but not all commands.  R is not a macro
language like Matlab.

> am also not looking for the debug() function. Here is what I would like to
> do:
>
> myFunction <- function() {
>   echo(TRUE);
>   x <- 3;
>   cat("x = ", x, "\n");
>   echo(FALSE);
> }

(That's not really correct R.  Line feeds are command separators as
well as ;, so you have a lot of empty commands in there.)

> Output:
> >myFunction()
> x <- 3;
> cat("x = ", x, "\n");
> x = 3
> >

You can only do this by modifying the function to print the commands,
as source() does.  Note that by time the function is being evaluated it
is already parsed, so in a sense there is no `command' to be echoed.
You can get a rough re-construction via deparse on expressions
(and a command line can include multiple expressions).

Why do you want to do this? A simple pre-processing of the function
to be

myFunction <- function() {
   cat("x <- 3", "\n")
   x <- 3
   cat("cat(\"x = \", x, \"\n\"), "\n")
   cat("x = ", x, "\n")
}

might be simplest, but I get the impression that you are thinking of R as a
macro language and there may be a more powerful approach to your real goal.


-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272860 (secr)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list