Clear R environment of all objetcs & packages - r

I tried this command
remove(list = ls())
I expect to clear all R environment (Objects, packages)

The simplest and, more importantly, the only reliable way of doing this is to restart R. That takes care of everything.
Just make sure you’re not accidentally saving the current R image when quitting R.
In RStudio, you need to set the option “Save workspace to .RData file on exit” to “Never”, and disable restoring upon restart — this is strongly recommended!
After that, make sure that any previously existing .RData files in your project’s folder are deleted (heads up: .RData is an invisible file so you won’t normally see it in a file browser; you can delete it via the command line).
To restart R from within RStudio, you can use “Session” › “Restart R” or Cmd+Shift+F10.

The answer was already out there :-) https://stackoverflow.com/a/7506112/7902133
According to this answer, the following code should work
lapply(paste("package:", names(sessionInfo()$otherPkgs), sep=""),
detach,
character.only = TRUE,
unload = TRUE)
You may also want to check the first answer for a full description.

The freshr package has consolidated the previous answers into one simple function. Install it via
install.packages("freshr")
and then run
freshr::freshr()
in your console and it will unload all packages and variables for you.

Related

In styler package of tidyverse, style_text prompts user input when first run

> packageVersion('styler')
[1] ‘1.3.2’
> style_text("A <- 1")
The R.cache package needs to create a directory that will hold cache files. It is convenient to use ‘C:\Users\A0765618\AppData\Local\R\R.cache’ because it follows the standard on your operating system and it remains also after restarting R. Do you wish to create the 'C:\Users\A0765618\AppData\Local\R\R.cache' directory? If not, a temporary directory (C:\Users\A0765618\AppData\Local\Temp\Rtmp6z4Eit/.Rcache) that is specific to this R session will be used. [Y/n]:
How can I run this functionally initially without this prompt? Can I set the answer to the prompt prior to calling? For example, how can I set it to n so that no prompt is needed?
This function will be called in a shiny app, so this prompt, which appears in the console will cause a bug.
TLDR;
put this before you call {styler} where the directory should already exist:
options(R.cache.rootPath = '/path/to/your/cache/dir')
You have the following options:
Deactivate the cache altogether
First of all, you can get rid of the caching problem by deactivating it altogether with styler::cache_deactivate(). Then, the prompt should not show up. To make this permanent, put this line in your .Rprofile.
Setting up the cache programmatically
However, if you want to benefit from the speed up the cache brings in your setting, you can set it up programmatically. I am just updating the docs for it (if you have comments please let me know):
In some cases, you want to avoid the interactive prompt described above. In that situation, you can set the path to the cache with the R option R.cache.rootPath or the environment variable R_CACHE_ROOTPATH to an existent path before you call the {styler} API. This should avoid the prompt. R.cache::setCacheRootPath("/path/to/cache") is also programmatic but will probably give the prompt anyways if called interactively.
So just do options(R.cache.rootPath = '/path/to/your/cache/dir').
You can also silence the pretty color warning (if you don't want to install it) with setting the option styler.colored_print.vertical as described in help(print.vertical, package = 'styler').
In addition, there is a styler.quiet option in styler > 1.3.2 but it likely won't have any impact because what you are seeing is directly coming from {R.cache}.
R.cache::setCacheRootPath(getwd())
Does indeed produce an undesirable message and prompt:
The R.cache package needs to create a directory that will hold cache files. It is
convenient to use '<xxxx>/Caches/R/R.cache' because it follows the standard on your
operating system and it remains also after restarting R. Do you wish to create the
'<xxxx>/Caches/R/R.cache' directory? If not, a temporary directory (/var/folder
/47/4_fn5xyx01b8_8bnyn8cpv3c0000gn/T//RtmpdO3NGa/.Rcache) that is specific to this
R session will be used. [Y/n]:
But, taking the hint in the prompt,
R.cache::setCacheRootPath("<xxxx>/Caches/R/R.cache")
runs without error or warning.
Then, after installing the prettycode package,
style_text("A <- 1")
produces
A <- 1
without message or warning.
Is it worth dropping a note to tidyverse asking for a styler.silent option?

How do I automatically have some code run everything I open up RStudio?

So for example, I want to set my global options as such:
options(stringsAsFactors = FALSE)
Sys.setenv(JAVA_HOME="C:/Program Files/Java/jre1.8.0_171")
for every RStudio session.
How can I write my code so that they are run at the beginning of each RStudio session?
Options
You can add the options script to your .Rprofile.
One of the easiest ways to access this is through the usethis library, specifically:
usethis::edit_r_profile()
The .Rproflie is always run at the start of a new session unless specifically told otherwise.
However, I only give you this with a MAJOR warning - adding code into your .Rprofile will prevent your R code from being reproducible. For this reason, I would strongly recommend you set the options call in a snippet in RStudio instead of using the .Rprofile, allowing for a keyboard shortcut to easily add to any script you run. While perhaps less convenient, I believe it's well worth the trade-off to keep your code fully reproducible. You can find more info on snippets with this support article from RStudio.
Envars
The Sys.setenv call would probably be suited well for using a .Renviron file.
Again, easily added with:
usethis::edit_r_environ()
Here is a nice reference to better explain the full use of .Rprofile and .Renviron files: https://cfss.uchicago.edu/notes/r-startup/

Make R project Automatically open Specific Scripts

I am working in team, we mainly use R, I am quite used to use R project in Rstudio, which I like because when I open them I have all my scripts and everything at the right place. However when another member of the team opens one of my project it loads the values and data but does not open the R script (one can see that by physically clicking on the project through the windows explorer rather than using the menu at the top right in R). I guess something can be done in the .Rprofile but I did not find any command to open physically a script, I tried
file.edit("./Main.R")
but it did not open anything. It just got me the message :
Error: could not find function "file.edit"
As always,
Thanks for your help !
**EDIT
I tried to use
file.show
file.edit
shell.exec(file.path(getwd()), "Main.R"))
in the .Rprofile. Nothing worked.
Romain
You can use the following code in the .Rprofile file.
setHook("rstudio.sessionInit", function(newSession) {
if (newSession)
rstudioapi::navigateToFile('<file name>', line = -1L, column = -1L)
}, action = "append")
The rstudioapi library has the function navigateToFile to open a file in Rstudio. The problem is that the code in the .Rprofile runs before Rstudio initialization. To deal with this problem you can use the setHook function (from base package) to make the code execute after the Rstudio initialization.
file.edit requires the utils package
library(utils)
file.edit("Master.R")
However, if it opens in Notepad rather than RStudio you have the same problem as me. I've tried editing the editor= in all possible places: .RProfile, RProfile, RProfile.sites, with and without .First() function statements and calls. However, RStudio does not load the .R file in RStudio if told to. It may be linked to the .RData file being loaded after .RProfile. Bug? Or at least a feature RStudio should incorporate in their RProject file specification.

How do I make R run R Commander every time it starts up?

I used to have it set up that R commander plug-in would start up automatically every time I opened the R application, but I've upgraded R and can't remember how I did it.
Here is Scott Hyde's instructions for creating a shortcut to start R commander every time you start R.
Open up the C:\Program Files\R\R-2.10.1\etc (or similarly named version directory).
Edit the file Rprofile.site and add the following lines. The mylibs variable is a list of packages that you want starting up each time you run Rcmdr. Both lattice and MASS are depencies of Rcmdr and need to be loaded. If you load them this way, they are loaded SILENTLY!
defpack = getOption("defaultPackages")
mylibs = c("tcltk","car","lattice","MASS","Matrix")
if(Sys.getenv("RCMDR") == "TRUE") mylibs = c(mylibs,"Rcmdr")
options(defaultPackages = c(defpack,mylibs))
Next, copy the shortcut that is used to run R onto the Desktop. Right click on the file, and select properties Add the following to the end of the "Target:"
"C:\Program Files\R\R-2.10.1\bin\Rgui.exe" --sdi RCMDR=TRUE
Notice that the options are OUTSIDE of the quotation marks.
Change the name of the shortcut you just made to "Rcmdr"
Double click on it, and both R and Rcmdr start!
Recently started using R, and I was testing out the other solution given by #user123943, and it just couldn't seem to work out right. Thought maybe there'd be a simpler solution and tried it and it worked fine. All you need to do is:
Find the Rprofile.site file (it should be in an etc file somewhere inside your R program file) (e.g.: C:\Program Files\R\R-4.1.1\etc)
Edit the file (give yourself permissions to edit if required) by adding in library(Rcmdr) at the end of the file.
That's it! Quick and easy solution! If you decide to revert it back all you will need to do is remove the added code at the end of the Rprofile.site file :)
Of course, save the file before opening up R again!

Starting R and calling a script from a batch file

I have an R-based GUI that allows some non-technical users access to a stats model. As it stands, the users have to first load R and then type loadGui() at the command line.
While this isn't overly challenging, I don't like having to make non-technical people type anything at a command line. I had the idea of writing a .bat file (users are all running Windows, though multi-platform solutions also appreciated) that starts R GUI, then autoruns that command.
My first problem is opening RGui from the command line. While I can provide an explicit path, such as
"%ProgramW6432%\R\R-2.15.1\bin\i386\Rgui.exe"
it will need updating each time R is upgraded. It would be better to retrieve the location of RGui from the %path% environment variable, but I don't know an easy way to parse that.
The second, larger problem is how to call commands for R on startup from the command line. My first thought is that I could take a copy of ~/.Rprofile, append the extra command, and then replace the original copy of the file once R is loaded. This is awfully messy though, so I'd like an alternative.
Running R in batch mode isn't an option, firstly since I can't persuade GUIs to display themselves, and secondly because I would like the R console available, even if the users shouldn't need to use it.
If you want a toy GUI to test your ideas, try this:
loadGui <- function()
{
library(gWidgetstclck)
win <- gwindow("test")
rad <- gradio(letters[1:3], cont = win)
}
Problem 1: I simply do not ever install in the suggested default directory on Windows, but rather group R and a few related things in, say, c:/opt/ where I install R itself in, say,c:/opt/R-current so that the path c:/opt/R-current/bin will remain constant. On upgrade, I first renamed to R-previous and then install into a new R-current.
Problem 2: I think I solved that many moons ago with scripts. You can now use Rscript.exe to launch these, and there are tcltk examples for waiting for a prompt.
I have done similar a couple of times. In my cases the client was using windows so I just installed R on their computer and created a shortcut on their desktop to run R. Then I right click on the shortcut and choose properties to get the propertiest dialog. I then changed the "Start in" folder to the one where I wanted it to run from (which had the .Rdata file with the correct data and either a .First function in the .Rdata file or .Rprofile in the folder). There is also a "Run:" option that has a "Minimized" option to run the main R window minimized.
I had created the functions that I wanted to run (usually a specialized gui using tcltk) and any needed data and saved them in the .Rdata file and also either created .First or .Rprofile to run the comnand that showed the gui. The user double clicks on the icon on the desktop and up pops my GUI that they can work with while ignoring the other parts.
Take a look at the ProjectTemplate library. It does what you want to do. It loads used libraries from a batch file an run R files automatically after loading as well as a lot of other usefull stuff as well...
Using the answer from https://stackoverflow.com/a/27350487/41338 and a comment from Richie Cotton above I have arrived at the following solution to keeping a script alive until a window is closed by checking if the pointer to the window is valid.
For a RGtk2 window created and shown using:
library(RGtk2)
mainWindow <- gtkWindow("toplevel", show = TRUE)
Create a function which checks if the pointer to it exists:
isnull <- function(pointer){
a <- attributes(pointer)
attributes(pointer) <- NULL
out <- identical(pointer, new("externalptr"))
attributes(pointer) <- a
return(out)
}
and at the end of your script:
while(!isnull(mainWindow)) Sys.sleep(1)

Resources