[R] Trying to learn how to write a function... can't define a variable??

Berend Hasselman bhh at xs4all.nl
Fri Sep 7 21:18:01 CEST 2012


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




More information about the R-help mailing list