Re: [R] modifying arrays within functions

From: <Bill.Venables_at_csiro.au>
Date: Wed, 6 Feb 2008 09:26:53 +1000

I can feel a sermon coming on...

I'd like to emphasize Martin's warning below and encourage you to avoid this kind of construction. The problem is side effects. Some R functions do this (e.g. fix) but everyone understands why. The real problem, in my view, is deeper. The question you ask originally implies that you don't really want a function, you want a macro. R does not work comfortably with macros, it works with functions.

This in turn suggests to me you are trying to make R work like some other software environment, presumably one with which you are familiar. This is very understanble, but nearly always a bad thing. If you are new to R, as you say, I would encourage you to find out how R works and work with it, rather than try to may R work the way you would like it to do. You will always be fighting the system unless you do.

Here endeth the sermon.

Bill Venables.

-----Original Message-----
From: r-help-bounces_at_r-project.org [mailto:r-help-bounces_at_r-project.org] On Behalf Of Martin Elff
Sent: Wednesday, 6 February 2008 2:23 AM To: r-help_at_r-project.org
Subject: Re: [R] modifying arrays within functions

On Tuesday 05 February 2008 (16:51:41), Konrad BLOCHER wrote:
> Hi,
>
> I'm pretty new to R and seem to be having difficulties with writing a
> function that would change an array and keep the change after the
function
> finishes its work.
>
It seems you want this:

X<-array(1,dim=c(2,2))
addition<-function(a){

        X[1,1] <<- X[1,1]+a # not '='
}
addition(1)
X

     [,1] [,2]
[1,] 2 1
[2,] 1 1                            

Nevertheless I would advise against writing and using functions that have side effects outside their scope.
It is in general dangerous.

Best,

Martin



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.

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. Received on Tue 05 Feb 2008 - 23:32:38 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Wed 06 Feb 2008 - 02:30:11 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive