The functions
   f1 <- function(x) x <- x + 1
and
   f2 <- function(x) x + 1
both return the same value.  You can see
this by doing
   z1 <- f1(10) ; print(z1)
   z2 <- f2(10) ; print(z2)
or just
   print(f1(10))
   print(f2(10))

f1(x) does not automatically print its output when run
directly from the command line while f2(x) does because
assignment statements inhibit autoprinting.

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com


> -----Original Message-----
> From: Berend Hasselman [mailto:b...@xs4all.nl]
> Sent: Friday, September 07, 2012 12:47 PM
> To: William Dunlap
> Cc: wwreith; 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 21:32, William Dunlap wrote:
> 
> > 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.)
> 
> But then I don't understand this
> 
> z<-1
> ADD<-function(x)
> {
> x<-x+1
> }
> ADD(z)
> 
> doesn't give any output.
> But
> 
> z <- ADD(z)
> z
> 
> gives
> 
> [1] 2
> 
> just as
> 
> ADD <- function(x) x+1
> ADD(z)
> 
> does.
> 
> 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.

Reply via email to