On Thu, 13 Apr 2006, Duncan Murdoch wrote: > On 4/13/2006 11:38 AM, Rolf Turner wrote: >> I am trying to build a function in a context where the environment >> concept would appear to be useful. But I'm a bit foggy about this >> concept and would appreciate some pointers and advice. >> >> Basically the function I'm building, say foo(x,t), is a function of >> two variables). Depending on the value of t, foo will return one of >> the values f1(x), f2(x), ..., fk(x), where each of f1, ..., fk is a >> piecewise linear function (built using approxfun()). >> >> Now I want other functions to be able to get at these pwl functions, >> making use of a syntax of the form >> >> bar(y,foo) >> >> so that in the code of bar() I could have assignments like >> >> clyde <- get("f1",envir=environment(foo)) >> >> So rather than assigning f1, ..., fk in the body of foo, I would like >> to assign them in the environment of foo. >> >> I want to do something like >> >> environment(foo) <- melvin >> >> where melvin contains f1, ..., fk. But how do I create ``melvin'' >> so that it is acceptable to the foregoing assignment? > > Generally it's not necessary to explicitly set the environment. Here > the way to get what you want is to define f1 and foo in the same > environment; then environment(foo) (which defaults to the environment > where it was created) will contain f1. > > So you can have a function like this: > > makefoo <- function() { > f1 <- ... > f2 <- ... > foo <- ... > return(foo) > } > > and the environment of the call to makefoo() will live as long as foo does.
Can I also suggest local()? This does a similar thing in a perhaps more natural way. -- Brian D. Ripley, [EMAIL PROTECTED] Professor of Applied Statistics, http://www.stats.ox.ac.uk/~ripley/ University of Oxford, Tel: +44 1865 272861 (self) 1 South Parks Road, +44 1865 272866 (PA) Oxford OX1 3TG, UK Fax: +44 1865 272595 ______________________________________________ R-help@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