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

Ista Zahn istazahn at gmail.com
Fri Sep 7 22:43:48 CEST 2012


On Fri, Sep 7, 2012 at 3:16 PM, Rui Barradas <ruipbarradas at sapo.pt> wrote:
> Hello,
>
> Start by (re-)reading An Introduction to R, file R-intro.pdf in your doc
> directory. Chapter 10.
>
> You're just computing, not returning the result of that computation. Nor
> anything else, ADD() does not return a value.

Sure it does. help("function") says "If the end of a function is
reached without calling 'return', the
     value of the last evaluated expression is returned." This is why

(z <- ADD(z))
[1] 2

works.

Best,
Ista

 (See the example in R-intro,
> section 10.1)
> And you need to assign the return value to change the value of 'z' _outside_
> the function. R passes arguments by value, what happens inside functions
> stays inside functions. (R-intro, section 10.5, first sentence.)
>
> # Right way
> z <- 1
> ADD <- function(x){
>
>     x <- x + 1
>     x
> }
> ADD(z)  # returns 2
> z  # still 1
> z2 <- ADD(z)
> z2  # equals 2
>
> Hope this helps,
>
> Rui Barradas
> Em 07-09-2012 19:00, wwreith escreveu:
>
>> 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.
>>
>> Now if I were to do print(x+1) instead of x<-x+1 it does return 2, so the
>> function seems ok with x+1, but not ok with x<-. Is there a way to define
>> a
>> variable inside a function or am I violating some rule that I don't know
>> about?
>>
>> Thanks for the help!
>>
>> Will
>>
>>
>>
>>
>> --
>> View this message in context:
>> http://r.789695.n4.nabble.com/Trying-to-learn-how-to-write-a-function-can-t-define-a-variable-tp4642528.html
>> Sent from the R help mailing list archive at Nabble.com.
>>
>> ______________________________________________
>> R-help at 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 at 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.




More information about the R-help mailing list