In general functions changing global variables as a side effect is dangerous (i.e., often leads to programming errors and difficult-to-maintain code).
So, if the performance of the following is sufficient, it is what I would recommend. addition <- function(X, a) { X[1, 1] <- X[1, 1] + a X } X <- array(1, dim=c(2, 2)) X <- addition(X, a) Sometimes for performance reasons or when programming an event-driven user interface you need functions to alter global data as a side effect. In that case addition <- function(a) { X[1, 1] <<- X[1, 1] + a } -Ben > -----Original Message----- > From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] > On Behalf Of Konrad BLOCHER > Sent: Tuesday, February 05, 2008 10:52 AM > To: r-help@r-project.org > Subject: [R] modifying arrays within functions > > > 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. > > in other words > > I have an array of 1's X<-array(1,dim=c(2,2)) > > I want to add a number to X[1,1] by means of a function called addition. > What I am writing is: addition<-function(a){X[1,1]=X[1,1}+a} > but it doesn't seem to work > > Any ideas? Please? :) > > Thanks > > KB > > ______________________________________________ > R-help@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. The information transmitted in this electronic communication is intended only for the person or entity to whom it is addressed and may contain confidential and/or privileged material. Any review, retransmission, dissemination or other use of or taking of any action in reliance upon this information by persons or entities other than the intended recipient is prohibited. If you received this information in error, please contact the Compliance HelpLine at 800-856-1983 and properly dispose of this information. ______________________________________________ R-help@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.