Sourcing in Rprofile.site: How to find the location of the sourced file - r

I have a "copy deployed" installation of R with no R-specific environment variables set.
I want to source a file from within Rprofile.site:
source("how/to/find/this/file/my_settings.R")
Where could I place my my_settings.R file so that it can be found from within Rprofile.site no matter in which path Rprofile.site is installed?
BTW: I want to avoid an absolute path to my_settings.R this would work indeed. I'd prefer to use the same folder as Rprofile.site or a path relative to it to support copy deployment of R.
Edit 1: The problem is that getwd is always different depending on the current folder from which you start R

If you can't use absolute paths and that your working directory is not stable, one way is to use .libPaths or .Library.
By default your Rprofile should be in directory paste0(.Library,"/../etc/") or paste0(.libPaths()[2],"/etc/") so you can put your file there and source it with :
source(paste0(.Library,"/../etc/my_settings.R"))
source(paste0(.libPaths()[2],"/etc/my_settings.R"))
As far as I understand the first option is stable (I don't think one can change the value of .Library).
If you use the second option just make sure that if in the future you alter your .libPaths() you do it after sourcing your file.
See ?.libPaths for more info on default folders.

Related

How to run R projects / use their relative paths from the terminal without setwd() resp. cd

I'm kinda lost on that one:
I have set up an R project, let's call it "Test Project.Rproj". The beauty of R projects is the possibility to use relative paths (relative to the .Rproj file). My project consists of a "main.R" script, which is saved on the same level as the .Rproj file.
Additionally I have a directory called 'Output', where I want my plots and exported data to be saved. My "main.R" file looks like the following:
my_df <- data.frame(A = 1:10, B = 11:20)
my_df |>
writexl::write_xlsx(here::here("Output",
paste0("my_df_",
stringr::str_replace_all(as.character(Sys.time()), ":", ""),
".xlsx")))
My final goal is to automate the execution of the 'main.R' file using the Windows Task Scheduler. But in order to do so, I have to be able to run the script from the terminal. The problem here is the working directory. When opening an R project, all the paths are relative to .Rproj file. But in the terminal the current working directory is <C:\Users\my_name>. Of course I could manually set the working directory via cd "path\to\my\project. But I would like to avoid that.
My current call for the execution of the main.R file in the terminal is the following:
"C:\Program Files\R\R-4.1.0\bin\Rscript" -e "source('C:/Users/my_name/path/to/my/project/main.R')"
My two ideas for a solution are the following, but I am happy for other suggestions as well.
In order to replicate the usual use of a project: Is there a way to execute the .Rproj
file from the terminal? In order to create a similar environment as in RStudio, where all the relative paths are working, when executing scripts from the project afterwards?
There are two packages adressing the problem of relative paths: rprojroot and here, where the former is the basis for the latter. I am pretty sure that here does not provide the needed functionality. I tried adding here::i_am("main.R) to my main.R file, but the project root directory still is not found when executing in the terminal from a working directory outside the project.
For rprojroot to work, I think it is also necessary to have your current working directory somewhere within the project. But this package offers a lot of functionality, so I am not sure wheter I am overlooking something.
So I would be happy about any help. Maybe it is impossible and I have to change the working directory manually - then I would be glad to know that as well.
Some links I used in my research:
https://www.tidyverse.org/blog/2017/12/workflow-vs-script/
https://malco.io/2018/11/05/why-should-i-use-the-here-package-when-i-m-already-using-projects/
http://jenrichmond.rbind.io/post/how-to-use-the-here-package/
Thanks a lot!
Edit: My current implementation is an additional R script, where I manually set the working directory via setwd() and source the main.R file. However it is always suggested to avoid setwd, which is why this whole question exists.

Where should I set the variable PATH in R?

I constantly need to call Tex Live binaries for compilation in R. However after the upgrade of Tex Live distribution, the path to current binaries needed to updated manually in the PATH(Sys.getenv("PATH")) variable.
As a single user on a Ubuntu system, which file should I update the value in, so that R gets the PATH correctly irrespective of whichever directory R is launched from.
One point I still don't gather is from where does R gets its site-wide (I mean for all users, even if faulty in saying so) PATH variable set, because no such variable name as "PATH" occur inside any files (Renviron, Renviron.site, Rprofile.site) in either of "R_HOME/etc/" and user's home directory? I also haven't set Sys.getenv("R_ENVIRON") and Sys.getenv("R_ENVIRON_USER") values.
I'd appreciate anybody's input here.
#JeffreyGoldberg's solution was close, but not quite right.
Rprofile files are interpreted as R code
Renviron files can only contain name value pairs, and are not interpreted as R code
From the help for Startup:
Note that there are two sorts of files used in startup: environment files which contain lists of environment variables to be set, and profile files which contain R code.
I'm not sure if this question is asking specifically how one can set the site wide value of PATH, rather than PATH for one specific user, but there are three locations you can put these files.
A project directory (i.e., a directory you choose to launch R from)
HOME
R_HOME/etc
These locations are searched in the order numbered above. The first location can contain configurations specific to a project, the second contains those specific to a user, and the third, site wide configuration settings. When a file is found it is used, so local takes precedence over global. Don't think you can create a more specific version that simply updates what you've done in a more general configuration file. R_HOME/etc/Renviron is created on installation and should not be edited. You may create a file called R_HOME/etc/Renviron.site, but do not edit R_HOME/etc/Renviron.
To create a site wide value of PATH, you will want to set it in a file in R_HOME/etc. Here you can use either Renviron.site or Rprofile.site for the file name. For a file in R_HOME/etc, Do not use Renviron, Rprofile, .Renviron, or .Rprofile for the name of a profile or environment file in this location. You can find out what R_HOME is in an R session using R.home(), or Sys.getenv("R_HOME")
To create a PATH value for a single user, set it in a file in HOME, which you can find in your R session using Sys.getenv("HOME") or path.expand("~"). You can also just use "~" to refer to HOME. Here, an Renviron file should be ~/.Renvironand an Rprofile file ~/.Rprofile. Take note of the difference between how profile and environment files are named in your HOME directory vs. R_HOME/etc
To create a PATH for a single project, set it in a file in that project's top level directory. Name the files as you would in your home directory (.Rprofile or .Renviron).
If you are creating an Renviron file, the file should include the following line:
PATH=<your path>
< and > should not be included. An example would be:
PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
If you are creating an Rprofile file, the file should include the following line:
Sys.setenv("<your path>")
again, don't include "<" or ">". An example would be:
Sys.setenv("/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin")
There are various ways of doing this that get and edit a PATH variable (e.g., tack on a new path at the end, or the beginning). You can also use the strategy of setting an environment variable if it doesn't already exist and/or doesn't contain something you want it to. I've come to prefer just setting up my path simply, and coding it directly.
One final note, if you run R from a command line interface, environment variables may be inherited from your shell. RStudio also has its own startup sequence and may modify the end of your PATH variable. It should start as it is defined in your Rprofile or Renviron files. The R Console app itself has the fewest quirks with system environment variables, and should accept your path exactly as it is set with an Rprofile or Renviron file.
Edit: I should have tested before posting. What I describe below did not work. (Down voting my own answer is a strange thing.)
On my system (macOS, bash), R.app is not picking up my $PATH from my shell environment or .profile. However RStudio is picking it up. I do not understand the different behaviors.
One way to get consistent behavior would be to specify this in an Renviron file.
If you create a file named .Renviron in your come directory with a line like
Sys.setenv(PATH="/opt/local/bin:usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/Library/TeX/texbin")
(but of course with the path elements you need) that should give you consistent behavior.
The downside is that you need to manually maintain this. I suppose you could run a script from one of your other start up scripts that generated the .Renviron file. But either way, I consider this whole thing a work around in place of actually understanding where R picks up its environment from.

Copy .rmd file included in a Rstudio addin package to a user defined directory

I have a rstudio addin package located here.
One of the addins allows the user to define a directory and it will copy a file that is located in the package to that directory.
the file is located:
atProjectManageAddins/inst/Docs/RMarkdownSkeleton.Rmd
And I am trying to copy it to the user defined directory with something like this:
file.copy("inst/Docs/RMarkdownSkeleton.Rmd",
paste0(Dir, FolderName, "/Reports/", FolderName, "_report.Rmd"))
Where I am trying to copy it from where it is in the package, to where the user defines it to be (Based on two separate arguments Dir and FolderName).
But this doesn't seem to work. My assumption is that I am not referring to the package directory in the correct way. I've tried ./Inst/, ~/Inst/ and maybe a couple more. My assumption now is that there is a more systematic reason for my inability to get file.copy() to work.
Any suggestions? Is this even possible?
Note that if I run the function locally via source() and runGadget(), it works just fine. Only when the package is installed and I use the RStudio addins GUI where it references the intalled package, does it fail. Thus, I'm quite certain I am not correctly defining the file path for the installed .Rmd files.
Edit: I've changed to the following, based on Carl's suggestion (as can be seen on github), but the files are still not being copied over.
file.copy(system.file("Docs","Rmarkdownskeleton.rmd",package="atProjectManageAd‌​dins"),
paste0(Dir, FolderName, "/Reports/", FolderName, "_report.Rmd"))
system.file is the best function for getting a file from a package. I believe this should work for you:
file.copy(system.file("Docs","Rmarkdownskeleton.rmd",package="atProjectManageAd‌​dins"),
paste0(Dir, FolderName, "/Reports/", FolderName, "_report.Rmd"))
You got the right idea putting the files in inst/.
Use this code to copy the file from the package dir to the current dir :
file.copy(from = file.path(path.package("packagename"), "path/to/file"),
to = file.path("path/to/file"), overwrite = T)
file.path creates a path by concatenating the strings passed to it (OS-specific separators are automatically added).
path.package retrieves the path of a loaded package. Files presents in inst/ are copied at the root of the package dir when installed, thus "path/to/file" here should be the path relative to your inst/ dir.
overwrite can be used to overwrite the file if it already exists.
In your specific case, this should do the trick :
file.copy(file.path(path.package("atProjectManageAddins"), "Docs/RMarkdownSkeleton.Rmd",
file.path(getwd(), "Reports", paste0(reportName, "_report.Rmd")))

How can I set the latex path for sweave in R?

I would like to know how I can set the pdflatex path in R to use sweave. Because I have 2 different MikTeX installations and one is working properly. Please take into account that I am using R (RStudio) in Windows. I found some suggestion however, for Linux or Unix users.
thanks in advance
If you have multiple installs of LaTeX (i.e. MikTeX) and you want to use a specific one of these, then you need to make sure that R finds the one you need first. This means that you have to add the location of your preferred version of pdfLaTeX at the front of your PATH system environment variable.
If you do not have administrator rights in Windows, then you can use R's environment file to change the PATH variable for R only. See ?Startup in R for details on this process. Follow the following steps:
in R, check the output of Sys.getenv("R_ENVIRON"). This will return the full path to an existing environment file, but will be empty in most cases. If a file exists, skip to step 3 below.
if no path is returned in step 1, create a file Renviron.site in the folder R_HOME/etc where R_HOME is the path returned by Sys.getenv("R_HOME").
add a line to the environment file as follows: PATH=C:\\full\\path\\to\\the\\folder\\with\\pdflatex;"${PATH}" (the quotations marks are important)
restart R and check Sys.getenv("PATH") and Sys.which("pdflatex") returns the correct paths.
If you do not have rights to create a Renviron.site file in R_HOME\etc, then you can also create a .Renviron file in HOME (Sys.getenv("HOME")).

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