[R] Creating an environment for a function.

Rolf Turner rolf at math.unb.ca
Thu Apr 13 17:38:10 CEST 2006


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?

One way I ***could*** go about it would be to create melvin
as a list:

		melvin <- list(f1=f1,f2=f2,etc.)

Then I could do

		attach(melvin)
		environment(foo) <- as.environment(2)

This seems to work ... but it also seems unnecessarily convoluted.

I could also do

		assign("f1",f1,envir=environment(foo))
		assign("f2",f2,envir=environment(foo))
		etc.

after creating foo(), but this is tejous.  I think I must be missing
a point or three.  As I said, I don't really grok environments.

Given that what I want to do makes any kind of sense at all, can
someone start me off in the right direction?

				cheers,

					Rolf Turner
					rolf at math.unb.ca




More information about the R-help mailing list