On 27/12/2021 8:25 a.m., Duncan Murdoch wrote:
On 27/12/2021 8:06 a.m., Grzegorz Smoliński wrote:
Hi,

I know it is possible to find the environment in which some object
lives using the 'environment()' function and the name of this object,
but how to modify code of this object after this? Below is MRE:

You are misunderstanding the relation between environments and
functions.  However, your understanding is also being messed up by a bug
in R, so it's not entirely your fault.

Actually this isn't a bug in R, it is working as documented. For a detailed explanation, see the response to my bug report here: https://bugs.r-project.org/show_bug.cgi?id=18269 .

For a quick idea: "complex assignments" are assignments where there is a complex expression on the left hand side, e.g.

  environment(test)$test <- ...

The way these are documented to work (in the R Language Definition manual) makes intuitive sense when you are working with regular R objects, but environments are "mutable" objects: assigning them to a new name doesn't make a new copy, just a new reference. That causes the definition of the complex assignment above to work in an unintuitive way.

Conclusion: you should avoid using calls like environment(f) on the left hand side of assignments, especially as part of a larger expression. Break up the statement into steps like I did below:

    e <- environment(test)
    e$test <- eval(parse(text = "function() 2"))

The same advice would apply to a function that returned an R6 object or a mutable object from the methods package (which are really environments in disguise), as well as some other exotic objects.

Duncan Murdoch

______________________________________________
[email protected] mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to