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.  

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 returned." 

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.

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

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

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! 

Hope that helps, 
Erik Iverson 

______________________________________________
R-help@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.

Reply via email to