[R] Writing a workable function

Bill Venables William.Venables at cmis.CSIRO.AU
Tue Aug 15 02:03:58 CEST 2000

Charles Raux asks:

> After searching in R- Introduction, FAQ, help... I don't understand 
> this:
> I write a function in a file (.R):
> tt <- function(mc) { 
>   date()
>   mc <- read.csv2("machines.txt", na.strings = "")
>   date()
> }
> I source it in R and I type tt(). The answer is
> > tt()
> [1] "Mon Aug 14 11:18:25 2000"
> >
> The instructions following the first "date()" are ignored. Why?

This is a very common misunderstanding by people who come from
languages where macros are the norm rather than genuine functions.

When a function in R is executed all variables created or modified
within the function are local to the function and only the value of
the function is communicated to the wider calculation.  In your case
the value of the function is the second call to date() so all other
operations within the function are done, but ultimately lost.  Note
that the arguments are also not linked with the actual arguments, so
your use of mc as an argument is irrelevant.

What you seem to want to do is write a function to read in data and
perhaps to some extra bits and pieces to it afterwards that you have
not shown us yet.  The standard way to go about this would be to write
the function as follows:

tt <- function() {
    mc <- read.csv2("machines.txt", na.strings = "")
    .... (further operations on mc as needed) ....
    mc  # makes the final value of mc the value of the function

and you would call the function from the command line using

this.mc <- tt()

that is, you would assign the value of the function to some top-level
variable that you would then use in further calculations.

It is possible to write R functions so that they do behave like macros
in the style you might expect, but that is really taking a giant leap
backwards and I simply won't tell you how to do it...   :-)

Bill Venables.

Bill Venables,      Statistician,     CMIS Environmetrics Project
CSIRO Marine Labs, PO Box 120, Cleveland, Qld,  AUSTRALIA.   4163
Tel: +61 7 3826 7251           Email: Bill.Venables at cmis.csiro.au    
Fax: +61 7 3826 7304      http://www.cmis.csiro.au/bill.venables/

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