[R] local and global variables

Duncan Murdoch murdoch.duncan at gmail.com
Sun Jun 22 06:11:01 CEST 2014


On 22/06/2014, 6:00 AM, Ragia Ibrahim wrote:
> Dear group 
> I have some thing like the following code...
> ##start
> my_list (global object)
> 
> function 1
> {
> list1<-mylist
> 
> function2(list1)
> function3(list1)
> function4(list1)
> }
> 
> function2(list1)
> {
> assign values via <<- to the object items
> }
> 
> function3(list1)
> {
> assign values via <<- to the object items
> }
> # end
> 
> 
> why after finishing each function the object variable is NULL..how can i keep its values across functions

The reason is that <<- doesn't do what you think it does.  It is useful
in a very narrow context, but not the way you're using it.  For what
you're doing, you don't need it.  Here's a better way to get what you want:

Change function 1 to look like this:

list1 <- function2(list1)
list1 <- function3(list1)
list1 <- function4(list1)

and change functions 2, 3, 4 to not use <<-, but to return the modified
list, e.g.

function2 <- function(list1) {
 list1 <- ...
 list1
}

Duncan Murdoch



More information about the R-help mailing list