[R] Trying to learn how to write a function... can't define a variable??
Berend Hasselman
bhh at xs4all.nl
Fri Sep 7 21:46:48 CEST 2012
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
More information about the R-help
mailing list