Berend, The OP's ADD() is returning the new value of x, as do all of your alternatives. His problem is that he is not assigning the output of ADD to a variable, as in z <- ADD(z) Ordinary functions do not alter their arguments. There is no need for the 'x <-' in the definiton of ADD. It may as well be defined as ADD <- function(x) x + 1
(One can write a replacement function, used as f(x)<-value, that modifies its first argument, but that is a more advanced topic.) Bill Dunlap Spotfire, TIBCO Software wdunlap tibco.com > -----Original Message----- > From: r-help-boun...@r-project.org [mailto:r-help-boun...@r-project.org] On > Behalf > Of Berend Hasselman > Sent: Friday, September 07, 2012 12:18 PM > To: wwreith > Cc: r-help@r-project.org > Subject: Re: [R] Trying to learn how to write a function... can't define a > variable?? > > > On 07-09-2012, at 20:00, wwreith wrote: > > > I am just starting to experiment with writing a function and have run into > > what seems like a limitation or more likely a lack of understanding on my > > part. > > > > Very Simple Example: I want to define a function that does 1+1=2. > > > > z<-1 > > ADD<-function(x) > > { > > x<-x+1 > > } > > ADD(z) > > z > > output for z is 1 not the expected 2. > > > > expected ==> "desired" > > Your ADD is not returning the new value of x. > > Either > > ADD<-function(x) > { > x<-x+1 > x # return new value of x > } > > or > > ADD<-function(x) > { > x<-x+1 > return(x) # return new value of x > } > > or even > > ADD<-function(x) > { > (x<-x+1) > } > > Have a look in the R-intro manual section "Writing your own functions" > > Berend > > ______________________________________________ > 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. ______________________________________________ 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.