Remove a library from .libPaths() permanently without Rprofile.site - r

How can I permanently remove a library in R?
.libPaths()
[1] "\\\\per-homedrive1.corp.riotinto.org/homedrive$/Tommy.O'Dell/R/win-library/2.15"
[2] "C:/Program Files/R/R-2.15.2/library"
[3] "C:/Program Files/RStudio/R/library"
The first item is my corporate "My Documents" folder, and the apostrophe in the path from my surname is causing all kinds of grief when using R CMD INSTALL --build on a package I'm making, not to mention issues using packages installed there when I'm offline from the network.
I want to use C:/Program Files/R/R-2.15.2/library as the default instead, but I don't want to have to rely on an Rprofile.site.
What I've tried
> .libPaths(.libPaths()[2:3])
> .libPaths()
[1] "C:/Program Files/R/R-2.15.2/library" "C:/Program Files/RStudio/R/library"
That seems to work, but only until I restart my R session, and then I'm back to the original .libPaths() output...
Restarting R session...
> .libPaths()
[1] "\\\\per-homedrive1.corp.riotinto.org/homedrive$/Tommy.O'Dell/R/win-library/2.15"
[2] "C:/Program Files/R/R-2.15.2/library"
[3] "C:/Program Files/RStudio/R/library"
I thought maybe .libPaths() was using R_LIBS_USER
> Sys.getenv("R_LIBS_USER")
[1] "//per-homedrive1.corp.riotinto.org/homedrive$/Tommy.O'Dell/R/win-library/2.15"
So I've tried to unset it using Sys.unsetenv("R_LIBS_USER") but it doesn't persist between sessions.
Additional Info
If it matters, here are some environment variables that might be relevant...
> Sys.getenv("R_HOME")
[1] "C:/PROGRA~1/R/R-215~1.2"
> Sys.getenv("R_HOME")
[1] "C:/PROGRA~1/R/R-215~1.2"
> Sys.getenv("R_USER")
[1] "//per-homedrive1.corp.riotinto.org/homedrive$/Tommy.O'Dell"
> Sys.getenv("R_LIBS_USER")
[1] "//per-homedrive1.corp.riotinto.org/homedrive$/Tommy.O'Dell/R/win-library/2.15"
> Sys.getenv("R_LIBS_SITE")
[1] ""
I've tried Sys.unsetenv("R_LIBS_USER") but this also doesn't stick between sessions

Just set the environment variable R_LIBS in Windows to something like
R_LIBS=C:/Program Files/R/R-2.15.2/library
Restart R.

This is bit late response to the question, but might be useful for others.
I order to set up my own path (and remove one of the original ones) I have:
used .libPaths() inside R to check current library paths;
identified which paths to keep. In my case, it kept R's original library but removed link to my documents.
found R-Home path using R.home() or Sys.getenv("R_HOME");
R-Home\R-3.2.2\etc\Rprofile.site is read every time R kernel starts. Therefore, any modification will be persistent to every run of R.
Edited Rprofile.site by adding the following,
.libPaths(.libPaths()[2])
.libPaths("d:/tmp/R/win-library/3.2")
How it works?
First line remove all but one path (second from the original list), the second line adds an additional path. We end up with two paths.
note that I use Unix path notation despite using windows. R always use Unix notation, regardless of operating system
restarted R (using Ctr+Shift+F10)
This will work every time now.

Use this function in .Rprofile
set_lib_paths <- function(lib_vec) {
lib_vec <- normalizePath(lib_vec, mustWork = TRUE)
shim_fun <- .libPaths
shim_env <- new.env(parent = environment(shim_fun))
shim_env$.Library <- character()
shim_env$.Library.site <- character()
environment(shim_fun) <- shim_env
shim_fun(lib_vec)
}
set_lib_paths("~/code/library") # where "~/code/library" is your package directory
Original Source: https://milesmcbain.xyz/hacking-r-library-paths/

I have put the Sys.unsetenv("R_LIBS_USER") command in a .Rprofile file in my windows "own documents" folder. Seems to help. My problem was that being in an active directory environment made R upstart and package loading incredibly slow when connected via vpn.

If you want to do this at RProfile file (#library/base/R/), you can search the lines where R_LIBS_* environment variables are set (for e.g. Sys.setenv(R_LIBS_SITE=....) and Sys.setenv(R_LIBS_USER=.....))
You can also search the code .libPaths(), which sets the library tree. So you can achieve your goal by a combination of commenting, unsetting and setting the R_LIBS variables before the .libPaths() call as you wish. For e.g. Something like:
Sys.unsetenv("R_LIBS")
Sys.unsetenv("R_LIBS_USER")
Sys.setenv(R_LIBS_SITE = "D:/R/libs/site")
Sys.setenv(R_LIBS_USER = "D:/R/libs/user")
Sys.setenv(R_LIBS = "D:/R/libs")

Related

How do I force saveWidget to create a single file outside of RStudio?

In RStudio I can save my html widget to a single file with:
htmlwidgets::saveWidget(x,"filename.html",selfcontained=TRUE)
When running an R script with the above line through windows Task Scheduler (which calls Rscript.exe) this would generate a multi-file html (i.e. an html file with an associated directory of referenced stuff). Using RGui also failed to generate a single-file html.
These are the lines from an Rgui implementation that replicates the issue:
> library(leaflet)
> library(htmlwidgets)
> map <- leaflet::leaflet() %>% addTiles() %>% setView(lng=172.4,lat=-41,zoom=6)
> saveWidget(map,file="deleteme.html",selfcontained=TRUE)
Error in saveWidget(map, file = "deleteme.html", selfcontained = TRUE) :
Saving a widget with selfcontained = TRUE requires pandoc. For details see:
https://github.com/rstudio/rmarkdown/blob/master/PANDOC.md
> list.files(getwd(),full.names=FALSE, recursive=TRUE)
[1] "deleteme.html"
[2] "deleteme_files/htmlwidgets-1.5.3/htmlwidgets.js"
[3] "deleteme_files/jquery-1.12.4/jquery.min.js"
[4] "deleteme_files/leaflet-1.3.1/images/layers-2x.png"
[5] "deleteme_files/leaflet-1.3.1/images/layers.png"
[6] "deleteme_files/leaflet-1.3.1/images/marker-icon-2x.png"
[7] "deleteme_files/leaflet-1.3.1/images/marker-icon.png"
[8] "deleteme_files/leaflet-1.3.1/images/marker-shadow.png"
[9] "deleteme_files/leaflet-1.3.1/leaflet.css"
[10] "deleteme_files/leaflet-1.3.1/leaflet.js"
[11] "deleteme_files/leaflet-binding-2.0.4.1/leaflet.js"
[12] "deleteme_files/leafletfix-1.0.0/leafletfix.css"
[13] "deleteme_files/proj4-2.6.2/proj4.min.js"
[14] "deleteme_files/Proj4Leaflet-1.0.1/proj4leaflet.js"
[15] "deleteme_files/rstudio_leaflet-1.3.1/images/1px.png"
[16] "deleteme_files/rstudio_leaflet-1.3.1/rstudio_leaflet.css"
A clue to the cause is the error message returned after running the saveWidget function (though the web link provided no longer works). The error message points out that htmlwidgets::saveWidget function requires pandoc.exe application to be available for it to create a single-file html. If it is not available then it creates a multi-file html.
But I have pandoc.exe installed, as it comes with the RStudio bundle, which I use all the time.
As it turns out, the availability of pandoc.exe is checked by htmlwidgets::saveWidget using the rmarkdown::find_pandoc function. This checks for the existence of pandoc.exe in paths saved in the "RSTUDIO_PANDOC" and "PATH" environment variables and in the ~/opt/pandoc/ directory.
When using RStudio, the "RSTUDIO_PANDOC" environment variable is automagically set. It is not set when I run a script via Task Scheduler as, in that case I use Rscript.exe. When pandoc.exe is installed (it comes in the RStudio bundle) the PATH environment variable is not set so it can't be found that way either.
So how do I get saveWidget to save to a single html file when I'm not using RStudio?
One solution is to explicitly set the RSTUDIO_PANDOC environment variable.
Alternatively pandoc.exe could be added to the PATH environment variable.
Either of the above could be added to the .Renviron file.
Here is an example of the first approach:
> library(leaflet)
> library(htmlwidgets)
> map <- leaflet::leaflet() %>% addTiles() %>% setView(lng=172.4,lat=-41,zoom=6)
> Sys.setenv(RSTUDIO_PANDOC = "C:/Program Files/RStudio/bin/pandoc")
> saveWidget(map,file="deleteme.html",selfcontained=TRUE)
> list.files(getwd(),full.names=FALSE, recursive=TRUE)
[1] "deleteme.html"

R system.file does not work as documented? (Or is just confusing?)

I am very confused by the R manual. According to the help pages, the system.file function may be used to find files relative to their installed path
> system.file("help", "AnIndex", package = "splines")
[1] "/Library/Frameworks/R.framework/Resources/library/splines/help/AnIndex"
Ok, so then I would expect that a file in my own package would also be obtainable using the same mechanism, but:
> library(reindeer)
> system.file("inst","default_parmeters.xlsx",package="reindeer",mustWork = TRUE)
Error in system.file("inst", "default_parmeters.xlsx", package = "reindeer", :
no file found
This hacky version works though:
> file.path(system.file(package="reindeer",mustWork = TRUE),"inst","default_parmeters.xlsx")
[1] "/Library/Frameworks/R.framework/Versions/4.0/Resources/library/reindeer/inst/default_parmeters.xlsx"
I cannot see why? This behaviour seems very arbitrary to me right.

Bash equivalent of which in R

Is there a function in R to identify which library a package is installed in? (This is assuming that some packages are installed in a local directory, such as ~/R_libs)
For example, in bash one can simply input which [package name] and it will return the location that the [package name] is executing from.
I think you want find.package().
## path to package
find.package("base")
# [1] "/usr/lib/R/library/base"
## path to directory
dirname(find.package("base"))
# [1] "/usr/lib/R/library"
To find, for example, the path to package base (replace this with whichever package you want)
libs <- library()$results
libs[which (libs[,"Package"]=="base"), "LibPath"]
Here is another method using installed.packages:
You can find the path to the package library with the following:
# return a matrix of p by 16 where p is the number of packages you have installed
packageInfo <- installed.packages()
# pull out the path of the library where data.table is installed, for example:
packageInfo["data.table", "LibPath"]
[1] "<path from root>/R/win-library/3.2"
As mentioned in the comments by #procrastinatus-maximus, it would be more compact to use
installed.packages()["data.table", "LibPath"]
Calling installed.packages() causes R to hiccup (a super short delay), so if you are looking up multiple packages, or looking up further information about the packages, then saving the resulting matrix in a variable and pulling info from it directly has tended to be a little more pleasant in my experience.

Check if R is running in RStudio

I am looking for a way to test if R is being run from RStudio. For some reason I could find the answer on google yesterday but not today, but I think it had to do with testing if a certain system variable was set.
This is from ?rstudio:
# Test whether running under RStudio
isRStudio <- Sys.getenv("RSTUDIO") == "1"
There is also rstudioapi::isAvailable(), but checking this is not as reliable because RStudio doesn't seem to really need the rstudioapi package to work correctly.
Check the .Platform$GUI option for "RStudio"
is.rstudio = function(){
.Platform$GUI == "RStudio"
}
See:
http://thecoatlessprofessor.com/programming/detecting-if-r-is-in-rstudio-and-changing-rstudios-default-graphing-device/
There is no "running inside RStudio". RStudio is merely an IDE layer that wraps around R; at the end of the day it just launches the normal R executable you need to have on your $PATH anyway to operate RStudio.
As a proxy, and as R Studio You could test available.packages() for the 'manipulate' package though, or as a shorter version see if RStudio added itself to the .libPaths() content:
R> any(grepl("RStudio", .libPaths()))
[1] TRUE
R>
R>
Edit in May 2020 or eight years later The question does come up, and one can query a variety of things from within. Here is an example from the terminal of RStudio:
$ env | grep -i rstudio | sort
GIO_LAUNCHED_DESKTOP_FILE=/usr/share/applications/rstudio.desktop
PATH=[...redacted...]
RMARKDOWN_MATHJAX_PATH=/usr/lib/rstudio/resources/mathjax-27
RS_RPOSTBACK_PATH=/usr/lib/rstudio/bin/rpostback
RSTUDIO=1
RSTUDIO_CONSOLE_COLOR=256
RSTUDIO_CONSOLE_WIDTH=111
RSTUDIO_PANDOC=/usr/lib/rstudio/bin/pandoc
RSTUDIO_PROGRAM_MODE=desktop
RSTUDIO_PROJ_NAME=chshli
RSTUDIO_SESSION_ID=9C62D3D4
RSTUDIO_SESSION_PORT=13494
RSTUDIO_TERM=2BD6BB88
RSTUDIO_USER_IDENTITY=edd
RSTUDIO_WINUTILS=bin/winutils
$
Similarly, from within the R session:
R> se <- Sys.getenv()
R> se[grepl("rstudio",se,ignore.case=TRUE)]
GIO_LAUNCHED_DESKTOP_FILE /usr/share/applications/rstudio.desktop
PATH [...also redacted...]
RMARKDOWN_MATHJAX_PATH /usr/lib/rstudio/resources/mathjax-27
RS_RPOSTBACK_PATH /usr/lib/rstudio/bin/rpostback
RSTUDIO_PANDOC /usr/lib/rstudio/bin/pandoc
R>
Edit in Aug 2021 or nine years later As all the answers listed here in the different answer may still be too much for people, you can also install package rstudioapi from CRAN and then ask it via rstudioapi::isAvailable() which comes back TRUE for me inside RStudio and FALSE in ESS / standard R.
When I start RStudio it seems to have tools:rstudio in position 2 on the search path. This has a function "RStudio.version" which is undocumented but seems to return the RStudio version string:
> RStudio.version()
[1] "0.96.316"
So you can define:
is.RStudio <- function(){
if(!exists("RStudio.version"))return(FALSE)
if(!is.function(RStudio.version))return(FALSE)
return(TRUE)
}
and maybe use that.
As of today, there are a few packages which include functions to check whether RStudio is running:
rstudioapi::isAvailable()
assertive::is_rstudio()
(list is non-exhaustive)
The assertive and assertive.reflections packages, resp., do include additional functions to check for other IDEs, desktop/server versions of RStudio, and various R releases (e.g., alpha, beta, devel, release, patched, etc.)
To add to the number of nice guesses, here is a message from 2011 (Ice Age)
http://support.rstudio.org/help/discussions/problems/413-location-of-installed-packages
if (Sys.getenv("RSTUDIO_USER_IDENTITY")!= ""){
.libPaths(.Library) # Avoid additional libraries } else { # not rstudio ...
I find the following works for me
checkRstudio <- function () {
return ("tools:rstudio" %in% search())
}
I am sort of new to R myself, but I believe Rstudio necessarily loads the
package "tools:rstudio" in order to run.
Neat solution is now available through the startup package via the is_rstudio_console function:
startup:::is_rstudio_console()
[1] TRUE
It may be worth adding that this function checks for two environment variables, RSTUDIO, which was mentioned in the answer by #krlmr and RSTUDIO_TERM that doesn't seem to be mentioned across the preceding answers at the moment.
function ()
{
(Sys.getenv("RSTUDIO") == "1") && !nzchar(Sys.getenv("RSTUDIO_TERM"))
}
The most reliable way to detect whether code is running in the main RStudio R session (without relying on the rstudioapi package) is:
commandArgs()[[1L]] == "RStudio"
Some comments on other answers:
Checking environment variables may be insufficient, as the "RSTUDIO" environment variable will also be inherited by child R processes launched from the main R session.
RStudio does not initialize its R infrastructure until after R profile scripts are run (e.g. ~/.Rprofile), so checking things like .Platform$GUI == "RStudio" or "tools:rstudio" %in% search() or rstudioapi::isAvailable() won't give what you expect in that context.
On a Mac only the Sys.getenv answer works
platform x86_64-apple-darwin10.8.0
version.string R version 3.1.0 (2014-04-10)
Sys.getenv("RSTUDIO")=="1"
[1] TRUE
RStudio.version()
Error: could not find function "RStudio.version"
any(grepl("RStudio", .libPaths()))
[1] FALSE
.libPaths()
[1] "/Library/Frameworks/R.framework/Versions/3.1/Resources/library"

How do I set R_LIBS_SITE on Ubuntu so that .libPaths() is set properly for all users at startup?

I am setting up a cluster where all nodes have access to /nfs/software, so a good place to install.packages() would be under /nfs/software/R. How do I set R_LIBS_SITE so that this is automatically part of all users' R environment? I tried prepending to the path given for R_LIBS_SITE in /etc/R/Renviron but help(Startup) says "do not change ‘R_HOME/etc/Renviron’ itself", which I'm not sure is the same file since R_HOME expands to /usr/lib/R, but has no effect in any case. Making entries in the various Renviron.site and Rprofile.site files does not seem to have the desired effect. What am I missing here?
Some other questions have danced around this (here and here, maybe others), but people seem to settle for having a user-specific library in their HOME.
Make sure you have owner and/or group write permissions for the directory you want to write into.
The file /etc/R/Renviron.site is the preferred choice for local overrides to /etc/R/Renviron.
Another way is to simply ... impose the directory when installing packages. I tend to do that on the (bash rather than R) shell via this script derived from an example in the littler package:
$ cat bin/install.r
#!/usr/bin/env r
#
# a simple example to install one or more packages
if (is.null(argv) | length(argv)<1) {
cat("Usage: installr.r pkg1 [pkg2 pkg3 ...]\n")
q()
}
## adjust as necessary, see help('download.packages')
repos <- "http://cran.us.r-project.org"
#repos <- "http://cran.r-project.org"
## this makes sense on Debian where no packages touch /usr/local
lib.loc <- "/usr/local/lib/R/site-library"
install.packages(argv, lib.loc, repos)
and you can easily customize a helper like this for your preferred location. With the script installed in ~/bin/, I often do
$ ~/bin/install.r xts plyr doRedis
and it will faithfully install these packages along with their depends. The littler package has a similar script update.r.
follow-up on Dirk Eddelbuettel (thanks Dirk!)
an adaptation of Dirk's suggestion that may be run within R:
# R function to install one or more packages
Rinstall <- function(pkg) {
if (is.null(pkg) | length(pkg)<1) {
q()
}
if(.Platform$OS.type == "windows") {
lib.dir <- "c:/R/library"
} else {
lib.dir <- "~/R/library"
}
repos.loc <- "http://cran.us.r-project.org"
install.packages(pkg, lib.dir, repos.loc, dependencies=c('Depends','Suggests')) # make sure you get dependencies
}
Usage:
Rinstall(c("package1", "package2"))
Naturally you want to adapt the repos.loc and lib.dir based on your system. As I work on both Windows and Linux machines I also inserted a conditional statement to check which system I'm on.
P.S. Don't hesitate to simplify the code, I'm a total newbie.

Resources