Making R installation self-contained/user-independent - r

I'm trying to get R to ignore c:\users\name\documents and be completely self-contained/portable
Here's my directory structure:
.../R/R-2.1.2.2/...
.../R/r_user/
.../R/libs_site/
I updated my Rprofile.site as follows:
# Set the working directory
setwd( file.path( R.home() , ".." , "r_user" ) )
# set the home directory
Sys.setenv(HOME=file.path( R.home() , ".." , "r_user" ) )
# Set the site library folder
.Library.site = file.path( R.home() , ".." , "libs_site" )
when R launches, I run .libPaths() but I still see c:/users/...
So perhaps R isn't updating per the Sys.setenv above? Solutions?

In my experience, creating a file named Renviron.site did not work on all my Windows machines, whereas naming the same file .Renviron instead did work everywhere. Not sure why. So if you're having difficulty with the above suggestions, then try .Renviron for a name.
Please do not hesitate to critically comment about my suggestion, because while I am describing what has worked for me, it may have difficulties I am not aware of.
In my experience, the following has worked:
Both Windows and Linux Platform:
Setting R paths
Find out the default paths:
.libPaths()
Set the path temporarily (in a R script)
.libPaths( "F:/Rlib" )
where F could be the letter associated with, say, a USB drive.
Query paths (both Windows and Linux):
Sys.getenv('R_LIBS_USER')
Sys.getenv('R_LIBS')
Sys.getenv('R_USER')
Sys.getenv('R_DOC_DIR')
Sys.getenv('HOME')
Try also:
normalizePath("~")
Try also:
getwd()
setwd(dir)
getwd returns an absolute filepath representing the current working directory of the R process
setwd(dir) is used to set the working directory to dir.
Windows (Tested on: 7x64)
Create an environment file named .Renviron
place it in the working directory or home directory:
"C:/Users/username/Documents"
Some users have reported that the .Renviron file needed to be in "c:/users/username/" instead. If you're not sure where to place it, save the desktop history and see where the .Rhistory file is located. Then place your .Renviron file in the same location. To save history savehistory()
# Windows .Renviron file:
R_LIBS_USER="C:/R/library"
R_USER="C:/R"
R_DOC_DIR="C:/R"
HOME="C:"
Set global PATH
My Computer / Properties / Advanced System Settings / Environment Variables --> user variables --> Path --> Edit
c:\R;c:\R\library;
Linux (Tested on kUbuntu 12.10)
Create an environment file named Renviron.site
place it in:
/etc/R/
Query the paths to check that your system is reading the Renviron.site file.
# Linux Renviron.site file:
R_LIBS_USER="~/R/library"
R_USER="~/R"
R_DOC_DIR="~/R"
#HOME="/home" # may not be needed
Remark: afaik the file is read from bottom to top, so HOME is defined at the bottom. In my setup ~ is correctly assigned to /home/ so I omit that last line anyway.
If you use RStudio, you may also want to add an rsession.conf file in the RStudio program directory. The following has worked for me:
# Windows 7:
r-libs-user="C:/R/library"
# Kubuntu 12:
# r-libs-user=~/R/%p-library/%v

You could create file Renviron.site in [your R installation path]\etc with lines
HOME="${R_HOME}\..\r_user"
R_LIBS_SITE="${R_HOME}\..\libs_site"
which set second and third of your settings. First could be replaced by setwd(Sys.getenv("HOME")).

I used the Rprofile.site file in [your R installation path]\etc and added the following lines to make C:/R/library my default library location each time R is launched:
# set a site library
.Library.site <- file.path("C:/R/library")
.libPaths(.Library.site)
I tried the other answers here but none of them worked with R 2.13.1 on Windows 7 64.

adding this does the trick:
.Library.site = file.path( R.home() , ".." , "site-library" )
.libPaths(.Library.site)

Related

R project WD changes "on its own"

I'm working on a project involving several people. We are using GitHub and a Rproject to be able to work on this project on different computers.
But I'm facing a really weird issue when I try to load files and/or get my working directory:
When I type getwd() in R console, I indeed get the path where the project is saved on my computer
> getwd()
[1] "/media/Data/Documents/my_R_project"
When I save getwd() in an object, the WD is not the same and now moves to the path were the script are saved:
folderpath <- getwd()
> folderpath
[1] "/media/Data/Documents/my_R_project/R/Script"
I get the same issue when I try to load a file which is located in /media/Data/Documents/my_R_project/R/Data: when I use read_csv (or any other function like it) and write the file path as
read_csv("R/Data/file.csv") I get and error stating me that there is no such file in the directory /media/Data/Documents/my_R_project/R/Script/R/Data/.
How could I resolve this and make the WD used in read_csv() be the right one ("/media/Data/Documents/my_R_project") so that I don't have to specify the full path every time and that people on another computer can run my script?
I'm working on Ubuntu LTS 20.04
In the end, the error was due to a conflict between the WD of the project and the WD used when I knitted the .Rmd file. The problem was solved by changing the knit options and set its directory as the project directory.

Unable to set working directory using here package in R to another location

I have a series of pieces of R code which have been designed to be run on other computers. That is, all code is relative to a root directory, which contains a Rstudio project file, .Rproj. There are no absolute file paths. This works fine when I actually open Rstudio, load the .Rproj file and then run the code.
However some of my code takes hours to run, and I need to set multiple scripts to run one after the other. This means creating a .sh file, and running the R script in turn from the command line. However non of my programs run successfully from the command line, as the root directory is no longer set to that of the .Rproj file. I have read about the here package can be used, which will automatically set the root directory to where ever a .here file is located. This is not the case for me.
The working directory it automatically uses is the home directory I have on the computational cluster I am using. The area where all my files, including the .Rproj and .here files is located in a different directory in which I have a lot more space allocated. Both are accessible from a common parent directory, so I assumed there here() function would be able to locate the directory I want to actually use to run my work. But this is not the case.
Effectively, I would like to set the root directory to a location which is not the default root directory on the system I am using. I have put a .here file there, but this is not located by there here() function, which I believe is its primary objective. Any ideas on how to proceed?
EDIT: I am working on a UNIX system. R version 3.4.2.
My problem was similar, but not exactly the same as yours. Perhaps my solution will work for you. When I opened an RStudio project, I found that if I called "library(here)", the root directory is set where the .Rproj file is located and that "set_here" would not change that directory, despite the 'here' package documentation. Perhaps I was doing something wrong, but I decided to solve the problem with a simple R function that moves up the directory tree until it finds a ".here" file. It then loads the "here" package and that sets the root directory where I want it.
I use "touch .here" in a Terminal outside of R to set my root directory, and then call "init_here()" from my newly opened R project:
init_here <- function() {
`%!in%` = Negate(`%in%`)
files <- dir( all.files = T )
while ( ".here" %!in% files & getwd()!="/" ) {
setwd("..")
files <- dir( all.files = T )
}
library(here)
}
Use Case -
In Unix:
cd( '~/myRoot' )
touch( '.here' )
In RStudio, when I open a project, the calls look like:
R version 4.0.2 (2020-06-22) -- "Taking Off Again"
< R information removed for clarity >
[Workspace loaded from ~/myRoot/myProject/.RData]
> getwd()
[1] "/Users/me/myRoot/myProject"
> init_here()
here() starts at /Users/me/myRoot
> here()
[1] "/Users/me/myRoot"
>
I can now put a ".here" file at the root of each of my RStudio projects and set the expected root directory independently for each project. If you want to get fancy, you could put the function in each project's .Rprofile so that it runs whenever the project is opened. All of my projects have the .Rproj file in the directory above my "R" directory, so my .Rprofile looks like:
source("./R/init_here.R")
init_here()
Hope that helps.
Did you try simply adding a cd /the/path/where/you/put/the/files command in your shell script?
According to this documentation, here() "uses a reasonable heuristics to find your project's files, based on the current working directory at the time when the package is loaded". The "cd" (change directory) command in a shell script changes the current working directory.

How to create .Renviron file?

I need to use my user defined folder where I stored my packages. I have referred the link given below.
R libraries installation
I have applied the same but it didn't work for me. I have created a file called .Renviron with data R_LIBS=c:/Rpackages ,where my packages installed. But, still it is showing there is no such package 'RODBC' exists. Also, I put this file in my Documents folder in C drive and tried. That also gave the same error. Still the file type is showing as text document. How to change this file type?
On mac (or linux)
Open the terminal and type
touch $HOME/.Renviron
To open the file you just created, navigate through finder to /Users/<your-user-name>/.Renviron, or simply open the terminal and type
open $HOME/.Renviron
On windows
Click on start and open powershell. Copy this code into powershell
Add-Content c:\Users\$env:USERNAME\Documents\.Renviron "TEST_VARIABLE_1=my_username"
Add-Content c:\Users\$env:USERNAME\Documents\.Renviron "TEST_VARIABLE_2=123"
You'll now have a file called .Renviron located in the Documents folder. Close and reopen RStudio. Then run Sys.getenv('TEST_VARIABLE_1') to access the variable in R (obviously that works for any other environment variables you set as well).
It may be worth adding that package usethis now offers a series of function facilitating easy editing and opening of R startup files. Family of edit_* functions can be used to conveniently edit desired startup and configuration files. To edit .Renviron, which is appropriate place to store the relevant configuration use:
# Edit Renviron
usethis::edit_r_environ()
# You can also consider creating project-specific settings:
usethis::edit_r_environ(scope = "project")
Usethis provides other functions useful for managing R configuration. For instance in order to edit Makevars you can do:
# Edit .R/Makevars
usethis::edit_r_makevars()
Look at help(Startup) which has an example at the end:
## Example ~/.Renviron on Unix
R_LIBS=~/R/library
PAGER=/usr/local/bin/less
## Example .Renviron on Windows
R_LIBS=C:/R/library
MY_TCLTK="c:/Program Files/Tcl/bin"
## Example of setting R_DEFAULT_PACKAGES (from R CMD check)
R_DEFAULT_PACKAGES='utils,grDevices,graphics,stats'
# this loads the packages in the order given, so they appear on
# the search path in reverse order.
But note the spelling: Renviron with lower case e. Just use a text editor and edit the file. Also note that R has a variant in one of its system folder etc/ below its RHOME:
edd#bud:~$ R RHOME
/usr/lib/R
edd#bud:~$ cat $(R RHOME)/etc/Renviron.site
## Emacs please make this -*- R -*-
## empty Renviron.site for R on Debian
##
## Copyright (C) 2008 Dirk Eddelbuettel and GPL'ed
##
## see help(Startup) for documentation on ~/.Renviron and Renviron.site
# ## Example ~/.Renviron on Unix
# R_LIBS=~/R/library
# PAGER=/usr/local/bin/less
# ## Example .Renviron on Windows
# R_LIBS=C:/R/library
# MY_TCLTK="c:/Program Files/Tcl/bin"
# ## Example of setting R_DEFAULT_PACKAGES (from R CMD check)
# R_DEFAULT_PACKAGES='utils,grDevices,graphics,stats'
# # this loads the packages in the order given, so they appear on
# # the search path in reverse order.
edd#bud:~$
Hm. Looks like I wrote that for the Debian package and it does always exist. You can still copy it.
On Mac
The Renviron file is located in
/Library/Frameworks/R.framework/Versions/Current/Resources/etc/
Creating a .Renviron file in the User's home directory will not help.

Changing R options persistently

I want to change the prompt in R from > to R> and I know I should use the options command options(prompt="...") and it works, but then when I restart R the prompt is back to >.
Is there anyway to save the change so that it sticks?
Use .Rprofile file:
You can customize the R environment through a site initialization file or a directory initialization file. R will always source the Rprofile.site file first. On Windows, the file is in the C:\Program Files\R\R-n.n.n\etc directory. You can also place a .Rprofile file in any directory that you are going to run R from or in the user home directory.
At startup, R will source the Rprofile.site file. It will then look for a .Rprofile file to source in the current working directory. If it doesn't find it, it will look for one in the user's home directory. There are two special functions you can place in these files. .First( ) will be run at the start of the R session and .Last( ) will be run at the end of the session.
More details are here

How to change .Rprofile location in RStudio

I am working with a "factory fresh" version of RStudio on Windows 7. R is installed under C:/Program Files which means the default libraries are stored here, and the two locations contained in .libPaths() on startup are both within this folder.
I want to work with another R library (igraph). Since the C:\Program Files folder is write-protected, I have set up another area to work in: C:\Users\nick\R and installed the igraph library in C:\Users\nick\R\library. I can manually add this location to the .libPaths() variable and use the library with no problems.
However, my problem is getting RStudio to automatically add this location to the .libPaths() variable on startup. I read that I could add the relevant command to my .Rprofile file - but I couldn't find any such file (presumably they are not automatically created when RStudio is installed). I then created a file called .Rprofile containing only this command. This only seemed to work when the .Rprofile file was saved in C:\Users\nick\Documents (which is the path stored in both the R_USER and HOME environmental variables). What I would like is to have the .Rprofile file stored in C:\Users\nick\R.
I have read all the information in ?Startup and it talks about where to store commands that run on startup. But I just can't make this work. For example there seems to be no way to change the location of the home directory without reading a file stored in the home directory. I don't seem to have any .Renviron files and creating these myself doesn't seem to work either.
I would really appreciate an answer in simple terms that explains how I could go about changing where the .Rprofile file is read from.
In Windows, you set the R_USER profile by opening up a command line and running:
SETX R_PROFILE_USER "C:/.../.Rprofile"
Where (obviously) the path is the path to your desired .Rpofile. In R, you can check that it worked:
Sys.getenv("R_PROFILE_USER")
Should return the path you specified. Note that you likely need to have all R sessions closed before setting the R_USER variable.

Resources