Say I have an R project opened at the following directory /home/user/workarea/project1
. Now I have a nested directory structure underneath and I am writing a function that is supposed to perform logging from anywhere inside this project and I want this function to write into files that are located at the directory /home/user/workarea/project1/log
. I plan to pass the file path as an argument to this function. Now I know that this file will always be located under the /log directory in the project's main directory - but how do I automatically find out which is my project directory, so that I don't always specify relative paths with ..
. I wouldn't want to hard-code my local path /home/user/workare/project1
, but be able to detect this wherever I clone my project.
Asked
Active
Viewed 6,666 times
10

Jim Raynor
- 198
- 2
- 9
-
2get working directory? ``getwd()`` – Cyrus Mohammadian Nov 20 '16 at 22:19
-
2That would assume that I never change the working directory from the main project folder correct? – Jim Raynor Nov 20 '16 at 22:21
-
Im not sure Im clear on your question but getwd just spits out your current wd -emphasis on current. So if you have multiple subdirectories in your project directory, the default -when you open up a project -will be the main project's directory unless you've manually set a new working directory. I think. – Cyrus Mohammadian Nov 20 '16 at 22:24
-
You might want to check out the [rprojroot](https://cran.r-project.org/web/packages/rprojroot/index.html) package. – Kevin Ushey Nov 20 '16 at 23:02
-
4@KevinUshey Awesome! The function `rprojroot::find_rstudio_root_file()` is exactly what I was looking for. Why don't you set it as an answer and I will accept it. – Jim Raynor Nov 20 '16 at 23:15
-
@CyrusMohammadian There are cases when I would like to set everything relative to the rstudio root file but it may happen that the current working directory is not set to that location. The package Kevin suggested provides a function to capture exactly what I wanted. Thanks for your effort! – Jim Raynor Nov 20 '16 at 23:25
-
See also https://stackoverflow.com/q/30237310/4241780 for setting the root directory a rMarkdown document to the Project Home folder using `knitr::opts_knit$set(root.dir = rprojroot::find_rstudio_root_file())`. – JWilliman Jul 02 '18 at 21:58
2 Answers
8
It sounds like the rprojroot package will provide what you're looking for -- in particular, the find_rstudio_root_file()
function should provide what you need.

Kevin Ushey
- 20,530
- 5
- 56
- 88