Hello all,

I came across a behavior of R with environments that I'm not sure what is
causing it.
It involves changing variables that are found through using model.frame on a
formula inside a function.
I wonder if it's a "bug" or a "feature".  And in either case, how it might
be managed.


Here is a simple example:

# let's say we have an x and y variables:
temp_x <- rep(1,5)
temp_y <- c(1:5)
# we now create a function that will take a formula of y~x and will (try and
*fail* to) change "y" (only) inside the environment of this function:
foo1 <- function(formu)
{
print("Before changing the 'y' variable in the formula")
print(model.frame(formu))
 temp_y <- model.frame(formu)[,1] +10

the_txt <- paste(names(model.frame(formu))[1], "temp_y", sep = "<-")
 eval(parse(text = the_txt)) # jutter out y var so to be able to handle
identical values.

print("After changing the 'y' variable in the formula")
print(model.frame(formu))
 # why isn't it printing the new y I just created for the enviornment of
this function?

}
# running the function shows the problem:
foo1(temp_y ~ temp_x)

# If I'll try it using <<-, this will change the y in the global environment
(something I'd rather avoid)
# for example:
foo2 <- function(formu)
{
print("Before changing the 'y' variable in the formula")
print(model.frame(formu))
 temp_y <- model.frame(formu)[,1] +10

the_txt <- paste(names(model.frame(formu))[1], "temp_y", sep = "<<-")
 eval(parse(text = the_txt)) # jutter out y var so to be able to handle
identical values.

print("After changing the 'y' variable in the formula")
print(model.frame(formu))
 # why isn't it printing the new y I just created for the enviornment of
this function?

}
foo2(temp_y ~ temp_x)
temp_y



-------------------------------------------
I know this question is somewhat of an oddity, but I hope some of you might
help me understand what is happening here.

Best,
Tal






----------------Contact
Details:-------------------------------------------------------
Contact me: Tal.Galili@gmail.com |  972-52-7275845
Read me: www.talgalili.com (Hebrew) | www.biostatistics.co.il (Hebrew) |
www.r-statistics.com (English)
----------------------------------------------------------------------------------------------

	[[alternative HTML version deleted]]

