[R] scoping rules
joerg van den hoff
j.van_den_hoff at fz-rossendorf.de
Tue Jun 8 19:13:21 CEST 2004
is there a good way to get the following fragment to work when calling
it as "wrapper(1)" ?
#======== cut here==========
wrapper <- function (choose=0)
{
x <- seq(0,2*pi,len=100)
y <- sin(1.5*x);
y <- rnorm(y,y,.1*max(y))
if (choose==0) {
rm(fifu,pos=1)
fifu <- function(w,x) {sin(w*x)}
}
else
assign('fifu',function(w,x) {sin(w*x)},.GlobalEnv)
res <- nls(y ~ fifu(w,x),start=list(w=1))
res
}
#======== cut here==========
I understand, the problem is that the scoping rules are such that "nls"
does not resolve 'fifu' in the parent environment, but rather in the
GlobalEnv. (this is different for the data, which *are* taken from the
parent environment of the nls-call).
The solution to "assign" 'fifu' directly into the GlobalEnv (which
happens when calling 'wrapper(1)") does obviously work but leads to the
undesirable effect of accumulating objects in the workspace which are
not needed there (and might overwrite existing ones).
so: is there a way to enforce that "nls" takes the model definition from
the parent environment together with the data?
joerg
More information about the R-help
mailing list