Skip to content
Prev 78588 / 398502 Next

Assign references

Looking at what objects exist after the call to myFunk() should give you 
a clue as to what happened:

 > remove(list=objects())
 > myFunk<-function(a,b,foo,bar) {foo<<-a+b; bar<<-a*b;}
 > x<-0; y<-0;
 > myFunk(4,5,x,y)
 > x
[1] 0
 > y
[1] 0
 > objects()
[1] "bar"    "foo"    "myFunk" "x"      "y"
 > bar
[1] 20
 > foo
[1] 9
 >

I suspect that you might have slightly misinterpreted Thomas Lumely's 
explanations of how the <<- operator works in different situations (the 
LHS must exist if you are assigning using a replacement operator, e.g., 
as in "foo[1] <<- ...", but not when you are assigning the whole object 
as in "foo <<- ...").

But I really would suggest careful consideration of what might be the 
best way to approach your problem -- modifying global data from within a 
function is not the standard way of using R.  Unless you are very 
careful about how you do it, it is likely to cause headaches for 
yourself and/or others down the road (because R is just not intended to 
be used that way).

The standard way of doing this sort of thing in R is to modify a local 
copy of the dataframe and return that, or if you have to return several 
dataframes, then return a list of dataframes.

-- Tony Plate
Seeliger.Curt at epamail.epa.gov wrote: