[R] global object in user defined function

Katharine Mullen kate at few.vu.nl
Wed Oct 10 09:07:26 CEST 2007


If I understand your question, then you should just study some
examples/other people's code that initialize new objects as the return
values of functions.  There are two small examples below.  On the other
hand, if you really need a _global_ object, see help(assign).

## Example 1: last line is return value; this is a numeric
x <- function(y) {
	y + 1
}
## now newvar contains the return value of x(3); you can
## pass this object as an arguement to other functions
newvar <- x(3)

## Example 2: return a list of values
xx <- function(y) {
	return(list(z = y + 1, s = 100))
}
## can pull the list elements out of newvar later
newvar <- xx(3)
## e.g.,
z <- newvar$z

On Wed, 10 Oct 2007, Murray Pung wrote:

> I need an object created in a user defined function to be accessible to
> another user defined function. I am fairly certain the object is correctly
> created as it prints when I use the return() function, however the 2nd
> function seems unable to use it.
>
> I am guessing objects created in functions are not globally accessible, is
> this correct?
>
> What is an appropriate way to pass the object to the second function?
> (I have tried defining it as a parameter when calling the 2nd function from
> within the 1st).
>
> Cheers!
>
> --
> Murray Pung
> Statistician, Datapharm Australia Pty Ltd
> 0404 273 283
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> 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