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:
Folks, I've run into trouble while writing functions that I hope will create and modify a dataframe or two. To that end I've written a toy function that simply sets a couple of variables (well, tries but fails). Searching the archives, Thomas Lumley recently explained the <<- operator, showing that it was necessary for x and y to exist prior to the function call, but I haven't the faintest why this isn't working:
myFunk<-function(a,b,foo,bar) {foo<<-a+b; bar<<-a*b;}
x<-0; y<-0;
myFunk(4,5,x,y)
x<-0; y<-0;
myFunk(4,5,x,y)
x
[1] 0
y
[1] 0 What (no doubt simple) reason is there for x and y not changing? Thank you, cur -- Curt Seeliger, Data Ranger CSC, EPA/WED contractor 541/754-4638 seeliger.curt at epa.gov
______________________________________________ R-help at stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html