[R] Basic function output/scope question

David Winsemius dwinsemius at comcast.net
Mon Sep 21 17:47:15 CEST 2009


On Sep 21, 2009, at 11:29 AM, David Young wrote:

> Hello Group,
>
> I'm trying to learn R and am having a problem getting output from a
> function I'm trying to write.  The problem is clearly one of scope,
> but I can't find the documentation that tells me how to get around the
> issue.
>
> Here is an example of my problem.
>
> testfunc<-function(x)
> { y<-10
> print(y)
> print(x)
> }
>
> testfunc(4)

The print function calls done inside testfunc have side effects of  
printing to the console. See this additional code that demonstrates  
that the returned value is actually "x" which is the last evaluated  
object in the function. You should also look at the "return" function.

 > z<-testfunc(4)
[1] 10   # side-effect but NOT the returned value
[1] 4
 > z
[1] 4   # the returned value

?return

-- 
David.
>
> The variables x and y are accessible during execution of the function
> "testfunc" but not afterwards.  I've read through the Introduction to
> R, and the R language definition on functions, but do not see how to
> define the output of the function, or change the scope of a function
> variable using the R equivalent of a %global statement as would be
> done in SAS.  Can someone tell me either where I can look for more
> information or how to make x and y accessible to operations after the
> function is run?
>
> Thanks in advance for any suggestions.
>
>
>
> -- 
> Best regards,
>
> David Young
> Marketing and Statistical Consultant
> Madrid, Spain
> +34 913 540 381
> http://www.linkedin.com/in/europedavidyoung
>
>                          mailto:dyoung at telefonica.net
>
> ______________________________________________
> 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.

David Winsemius, MD
Heritage Laboratories
West Hartford, CT




More information about the R-help mailing list