[R] question

Martin Maechler maechler at stat.math.ethz.ch
Mon Jun 7 15:34:57 CEST 2004


>>>>> "Petr" == Petr Pikal <petr.pikal at precheza.cz>
>>>>>     on Mon, 07 Jun 2004 13:12:07 +0200 writes:

    Petr> Hi On 7 Jun 2004 at 12:57, zze-PELAY Nicolas
    Petr> FTRD/DMR/BE wrote:

    >> Hello,
    >> 
    >> I'd like to know if I can modify a constant value with a
    >> function.
    >> 
    >> Example :
    >> 
    >> a=4
    >> 
    >> f1<-function() {a=3}

    Petr> Simply use <<- in the function.
yes.

    Petr> But I am not sure if this is recommendable way of
    Petr> items manipulating in R. 

Thank you, Petr.  Indeed, I am even sure that it *is* not recommended:
Very much recommended is to write a function such that 

 1) it only uses its arguments (and no global variables) as input
 2) provides all its results as return() value, often a list().

There are exceptions to these rules, e.g. for plot() 
functions, "2)" will often not be true [and for print.*() methods,
the unwritten R standard asks for print.*(x, ....) to return(invisible(x))]
"1)" {and sometimes 2) as well} will be violated for UI (not only GUI)
functions. 

When working very large objects, it can make sense to
violate both "1)" and "2)".. -- but that's really for more
advanced programming.

Martin Maechler




More information about the R-help mailing list