Home > Software design >  How to change object from any environment?
How to change object from any environment?

Time:12-28

I would like to modify some code (or add / delete) in the environment where this code lives. I have found this topic really helpful: How to change on the fly a line of an existing function in R, but problem I have is that function I want to modify is not in the .GlobalEnv and I don't know what is the name of this environment.

This environment I'm thinking about could be described as a B environment from this answer on one of my previous question: What is an environment where exists all objects from all files sourced when running Shiny App?. So basically I would like to change some code in Shiny App. I managed to find the environment using environment() function, but I see I can't replace the code.

Perhaps my problem can be shown using this code:

test <- function() 1

test()
#> [1] 1

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

test()
#> [1] 1

.GlobalEnv$test <- eval(parse(text = "function() 3"))

test()
#> [1] 3

How can I make this line of code: environment(test)$test <- eval(parse(text = "function() 2")) to work? i.e. how to change the object using environment()?

@jpiversen let me kindly note you about this question.

CodePudding user response:

The problem lies with using test multiple times on the left hand side confusing $<- in "R version 4.1.2 (2021-11-01)" and presumably other versions of R as well.

1) A workaround would be to break the assignment into two statements.

test <- function() 1

test()
## [1] 1

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

test()
## [1] 2

2) Alternately use assign

test <- function() 1

test()
## [1] 1

assign("test", eval(parse(text = "function() 2")), environment(test))

test()
## [1] 2

Note

  1. The examples work the same if we use function() 1 and function() 2 in place of eval(parse(text = "function() 1")) and eval(parse(text = "function() 2")) .

  2. This question or variations of it was also posted on r-help and r-devel and r-bugs and in the last one Luke Tierney indicated that this is due to the way $<- works with environments (see that link for detailed explanation) but the bottom line is that they feel it would be too disruptive to show a warning or error or to change it at this point.

  • Related