[R] Basic function output/scope question

David Young dyoung at telefonica.net
Tue Sep 22 11:25:43 CEST 2009


Thanks Erik, Schalk, Patrick, and David for you helpful advice.  I
hope I'll, at some point, I'll become versed enough in R to return the
favor.


-- 
Best regards,

David Young
Marketing and Statistical Consultant
Madrid, Spain
+34 913 540 381
http://www.linkedin.com/in/europedavidyoung



Monday, September 21, 2009, 5:42:35 PM, you wrote:

EI> Hello, 

>> 
>> testfunc<-function(x)
>> { y<-10
>> print(y)
>> print(x)
>> }
>> 
>> testfunc(4)
>> 
>> The variables x and y are accessible during execution of the function
>> "testfunc" but not afterwards.  

EI> In R, expressions return values.  When you define a function, ?function says that, "If the end of a function is reached without calling 'return', the value of the last evaluated expression is
EI> returned." 

EI> So you are correct, 'x' and 'y' are local variables, and by all accounts they should be.  If you want their values accessible, simply return them.

EI> ## return just y
EI> testfunc2 <- function(x) {
EI>    y <- 10
EI>    y
EI> }

EI> ## return both x and y 
EI> testfunc2 <- function(x) {
EI>    y <- 10
EI>    list(x, y)
EI> }

EI> There are ways to make x and y global from within a function, but in general that is not the R way to do things! 

EI> Hope that helps, 
EI> Erik Iverson




More information about the R-help mailing list