Why doesn't RStudio clear its Global Environment when something goes wrong? - r

Using R Version 4.0.2 and RStudio Version 1.3.1056
This is honestly one of the strangest features I've seen in RStudio, and I suppose there's probably a good reason for it to be there, but I'm currently not seeing it and I feel that it can lead to a lot of issues of misleading data.
Basically, to my understanding, when you create and open an R project in RStudio, RStudio creates a Session with a Global Environment.
Every time you run something, this is added to the Global Environment, I assume it's done as a cached value.
However, I've encountered situations where this feature leads to either:
Outdated/wrong values being shown in my tests.
Cases where a function stops working altogether after changing 1 piece of code, executing the new code, then undoing the change.
functions "bleeding into" other files without importing/sourcing them.
Case 1 and 2 obviously leads to a lot of issues while testing. If you try to run a test like
test <- someFunction()
test #to display the value of the test
If the code is correct, the test will execute and the results of test will be stored in the Global Environment.
However, if you then proceed to break the code and run the test again, since test already has a value stored in Global Environment, that old value will print, even though the function failed and thus didn't return anything. Of course if you go above on the console feed, you might run into a line after test <- someFunction() saying "someFunction failed for X reason", but I still think it's both pretty misleading and not very intuitive. Sometimes the result of a function is really large and it's complicated to scroll all the way up the console to see if the code exited with an error, whereas other IDEs would simply immediately tell you at the end of the console that the code failed, and not print the old and outdated value.
Example: Running the proper code.
Running the code after having changed is.na to the non-existent is.not.na.
Notice how it's still printing the old value belonging to the previous version of the function.
The third case can also lead to misleading scenarios.
If you execute a function in any file within your session, the function is stored in the Global Environment. This allows you to call the function from any other file, even if you haven't added a source statement at the top to load the file containing that function.
Once again this can lead to cases where you inadvertently change/add a new function on file B without running it, then try to invoke the function from file A and you get unexpected results because you were actually invoking the old/outdated function, and the Global Environment has no idea about the changes to the old one or the new function.
All of these issues are rather easy to fix, but I think that's a bit beyond the point. Why is this a feature in general? Why isn't the Global Environment emptied upon errors in execution? I know that you can manually empty the GE whenever you want, but it seems odd to me that the IDE doesn't do it on its own, or, to my knowledge, that it doesn't provide you with an option for it to do it.
I can imagine that it provides some benefit at runtime, but is it really that significant that it can justify these behaviors?

Related

Stop RStudio always opening source viewer when in debug mode when evaluating R code

I often code functions in the following way by creating a basic function, entering debug mode, and then writing the function in debugmode. E.g.,
myfun <- function(x) print(x)
debugonce(myfun)
myfun("test")
The benefits of this is that I can get real time feedback on whether my code is working with the arguments passed to it.
However RStudio appears to have recently changed it's behaviour to make this more difficult. I recently upgraded to 2021.09.0 Build 351.
Previously, it would open the Source Editor when you call this command.
But if you closed this screen, you could return to your code, edit the code, evaluate code, and so on without the viewer re-appering.
However, now it seems to reappear every time you evaluate your code.
For instance, if I close the viewer, go back to my main script, and evaluate x, the Viewer opens back up.
This is super annoying for someone used to editing and evaluating code while in debugmode using the source script file.
Is there any way of entirely disabling the Source Editor view in Rstudio? Or alternatively, is there a way of being able to edit and evaluate code without the Source Editor constantly re-appearing in Rstudio (like how it used to work)?
My current fix is to downgrade to Version 1.3.1093, where you could edit and evaluate code without the Viewer constantly re-appearing. But it would be a shame to miss out on future upgrades.
This issue was principally a bug that has now been fixed.
At time of posting, downloading a daily build fixes the issue, but eventually this fix will be incorporated into beta and standard builds.
https://github.com/rstudio/rstudio/issues/9943

Does utils:::fixInNamespace make permanent changes? R

I am using a 3rd party package for a script, I want to tweak one of the functions so that one of the variables created by the function is assigned to the global environment.
I did this previously by doing
fixInNamespace("the_function","the_namespace","namespace:::the_function")
And it opened a pop-up window where I could add my one line of code
assign("global_variable", "variable", envir = .GlobalEnv)
It worked like a charm, I could then write the rest of my script to use this newly formed variable.
I have tried to run the code again one day later and it can't find the global variable, and if I run
namespace:::the_function
It shows me the function code without my edit, why has it reverted back to its previous form? Is fixInNamespace not permanent?
Thanks,
Ryan
No, it's not permanent. It will last until the namespace is loaded again. Normally namespaces stay loaded for an entire R session, so your change will last for the session. (It is possible to unload a namespace without quitting R; in that case your change would be lost as soon as the namespace was unloaded.) In any case, the next time the package is loaded, it will be the original version of the namespace.
There are a couple of ways to make your change permanent, but doing this is not a good idea. One way is to call assignInNamespace from your startup code (see ?Startup for possibilities). Another is to edit the R source code, and build your own custom copy of R.
Neither of these is a good idea in the long term. Some future version of R might change the function you've modified, and then you'll end up with a modified obsolete version.

Getting list of windows in Tk and destroying specific ones (R)

I was wondering if it is possible to get a list of windows in Tk, and destroy specific ones. I am working in R using the tcltk interface, and am calling a function written by someone else a long time ago (that I cannot edit) which is producing additional windows that I don't want.
From the documentation here, it seems that new Toplevel windows are children of .TkRoot by default. I know that Python has a winfo_children method, which I was thinking of trying to call on .TkRoot but I don't think that method is implemented in the tcltk library. I tried using tcl("winfo", "children", .TkRoot) but I am getting an error: [tcl] bad window path name "{}" (I'm not familiar with actual tcl, so I'm probably messing this command up).
Additionally, if there is a way to call winfo children, what's the best way to process the result to identify specific windows and then destroy them?
Looking at the R sources, I see that you should be doing:
tkwinfo("children", .TkRoot)
Except that I think that won't work either, as .TkRoot doesn't have a corresponding widget on the Tk side of things. Instead, use the string consisting of a single period (.) as the root of the search; that's the name for the initial window on the Tcl side of things. And I suspect that you'll just get back a raw Tcl list of basic Tk widget names without the R wrapping as I just can't see where that conversion is applied…
Be aware that the results may include widgets that you don't expect, and that you need to call it on every window recursively if you want to find everything.

R is there a way to dynamically update a function as you are building it

I am very new to R and I am using RStudio. I am building a new "user-defined" function, which entails a huge amount of trial and error. Every time I make the slightest change to the function I need select the entire function and do crtl+Enter in order to "commit" the function to the workspace.
I am hoping there is a better way of doing it, perhaps in a separate window that automatically "commits" when I save.
I am coming from Matlab and am used to just saving the function after which it is already "committed".
Ctrl+Shift+P re-runs previously executed region, so you won't have to highlight your function again. so this will work unless you have executed something else in the interim.
If you wan to run some part of your code in RStudio you simply have to use Ctrl+Enter. If the code were run every time you saved it, it could have very bad effects. Imagine that you have a huge script that runs for a long time and uses much computer resources - this would lead you to killing R to stop the script every time you saved it!
What you could do is to save script in external file and than call it from your main script using source("some_directory/myscript.R").

R JIT compiler - is there a way to automatically pre-compile all functions in a script? (for use with shiny)

Is there a way to get R to precompile all functions in a script?
The reason it matters is because the script is code for rshiny. I'd like to push forward the byte compiling to occur when the server starts up rather when the user is requesting a page.
I know cmpfun() could be used to compile one function at a time and modify function calls accordingly, but I'd like to do this without maintaining the extra boilerplate code if it's possible.
You should be able to use the JIT from compiler with:
library(compiler)
enableJIT(3)
or set the environment variable R_ENABLE_JIT to non-negative (3 is the highest amount of compilation). I did a quick experiment with my Shiny app and this seemed to produce no benefit at all, so maybe something is not working correctly. This page provides a few more details on R compilation options.

Resources